0

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?

2 Answers 2

2

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)));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, friend! That is just what I needed. Only thing is the return type must also be MvcHtmlString. Thanks again.
Welcome mate! Please consider the answer as accepted for other people to know the right answer.
Indeed. I am waiting until I am able to accept the answer...it says I cannot do that for another 3 minutes! Crazy stuff...
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.