How can I return razor markup from a helper?

342 Views Asked by At

Recently I wrote a javascript library to reduce the amount of copy paste that I was doing. I feel like any time I copy paste code there is an opportunity to make it generic so I can re-use it.

Upon making my library, I wanted to use it in a .cshtml view. So, I used the script link and vuala, it was available. However, Visual Studio 2010's IntelliSense was not really helping at all. In fact, all it showed was the regular javascript options.

I set out to make IntelliSense work with my library. After searching high and low I figured it out (Thanks @SLaks). The linked answer to a js IntelliSense question was to surround the script link with a razor @if(false){<script>} in order to have IntelliSense work with the linked script in that view.

So, I thought,

Should all script links in Visual Studio 2010 for razor be surrounded with this markup?

@if (false)
{
 <script src="/Scripts/r.js" type="text/javascript"></script>
}else{
 <script src="@Url.Content("~/Scripts/r.js")" type="text/javascript"></script>
}

It looks good to me, so I started to incorporate it only to find that I was copy pasting again. I figured I could make a "simple" helper to use, maybe @Html.Script(source). Unfortunately, I was uncertain of how to return razor markup from a helper.

I tried this:

    public static void Script(
this HtmlHelper html, string source)
    {
        html.ViewContext.Writer.Write("@if(false){}else{}");
    }

But it just writes the string out to the screen :(

How can I return razor markup from a helper? OR, is there another process that I can use to accomplish making this re-usable?

1

There are 1 best solutions below

0
On

You can't render a Razor markup produced in a helper. The razor engine first parses the razor code, then performs helpers. Helper's results can be used only to produce html markup.