Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my custom HTML Helper result getting html encoded?

I've got the following custom html helper in asp.net mvc 3

public static string RegisterJS(this HtmlHelper helper, ScriptLibrary scriptLib)
{
   return "<script type=\"text/javascript\"></script>\r\n";
}

The problem is that the result is getting html encoded like so (I had to add spaces to get so to show the result properly:

   &lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

This obviously isn't much help to me.. Nothing I've read says anything about this.. any thoughts on how I can get my real result back?

like image 848
Shane Courtrille Avatar asked Jan 26 '11 20:01

Shane Courtrille


People also ask

What is custom HTML helper?

HTML Custom Helpers HTML helper is a method that returns a HTML string. Then this string is rendered in view. MVC provides many HTML helper methods. It also provides facility to create your own HTML helper methods. Once you create your helper method you can reuse it many times.

What does HTML helper class generate?

The HtmlHelper class generates HTML elements. For example, @Html. ActionLink("Create New", "Create") would generate anchor tag <a href="/Student/Create">Create New</a> . There are many extension methods for HtmlHelper class, which creates different HTML controls.

Can we create custom HTML helper?

Creating HTML Helpers with Static MethodsThe easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create a new HTML Helper that renders an HTML <label> tag. You can use the class in Listing 2 to render a <label> .


1 Answers

You're calling the helper in a Razor @ block or an ASPX <%: %> block.
These constructs automatically escape their output.

You need to change the helper to return an HtmlString, which will not be escaped:

return new HtmlString("<script ...");
like image 78
SLaks Avatar answered Oct 22 '22 01:10

SLaks