Matt
Matt

Reputation: 6963

ASP.NET MVC 3: Extension method on UrlHelper/HtmlHelper encodes to HTML

I have written some extension methods for UrlHelper in order to more easily load a , or tag. However, it seems that it renders to literal text in the browser. Here is what I have:

public static string Script(this UrlHelper helper, string scriptPath)
        {
            return string.Format(@"<script src=""{0}"" type=""text/javascript""></script>", helper.Content(scriptPath));
        }

Here is my .cshtml code:

@section HeadContent
{
    @Url.Style("MyStyleName")
    @Url.Script("MyScriptName")
    @Url.MetaKeywords("My Keywords")
    @Url.MetaDescription("Some Description")
}

and it comes out in the browser with &lt;script [etc, etc]&gt;

If I don't use the extension methods, it will as expected, work correctly... how can I make it work with my extensions?

Upvotes: 0

Views: 1968

Answers (2)

Dallas
Dallas

Reputation: 2237

All HTML helpers need to return MvcHtmlString. If you just return a string, it will be treated as an untrusted value and will be HTML-encoded.

Upvotes: 2

Abdul Munim
Abdul Munim

Reputation: 19217

Try this:

public static string Script(this UrlHelper helper, string scriptPath)
{
    return MvcHtmlString.Create(string.Format(@"<script src=""{0}"" type=""text/javascript""></script>", helper.Content(scriptPath)));
}

Upvotes: 2

Related Questions