2

I have a function in c # where I use StringBuilder and added JavaScript code, this is my helper:

public static string RegisterJS(this System.Web.Mvc.HtmlHelper helper, string scriptLib)
{
    StringBuilder JavaScript = new StringBuilder();
    JavaScript.AppendFormat(@"<script type= ""text/javascript"">{0}", Environment.NewLine);
    JavaScript.AppendFormat(@"var toolbar = new toolBarObject('toolbarObj');{0}", Environment.NewLine);
    JavaScript.AppendFormat(@"toolbar.disableElements('" + scriptLib + "', true);{0}", Environment.NewLine);

... ... JavaScript.AppendFormat(@"{0}", Environment.NewLine);
return JavaScript.ToString(); }

This function is called to load an application in Asp.Net MVC4 within a section:

as follows:

@section ToolBar{
  <h2>aqui debo cargar mi javascript</h2>
   @Html.RegisterJS("Personal")
}

I run the program and display the page code i have this:

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

and I should have this:

<script type= "text/javascript">

this happens in all lines of the function

how I can solve this problem

0

2 Answers 2

1

I would suggest wrapping this in Html.Raw

@section ToolBar
{
 <h2>aqui debo cargar mi javascript</h2>
 @Html.Raw(Html.RegisterJS("Personal"))
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Lostdreamer - Html.Raw is handy :)
Yeah, you could also have the function to return HtmlString instead, razor wouldn't encode it this way.
@Lostdreamer - That is another valid approach, Raw simply returns an HtmlString instance. There are also ways of injecting the whole razor statement as well from a helper.
1

The @ symbol in razor syntax does HTML-encoding of the result.

You can prevent this by returning an IHtmlString from your method, which essentially communicates to the @ symbol that your text does not need to be encoded.

The easiest way to do this would be to replace your last line with:

return MvcHtmlString.Create(JavaScript.ToString());

Be careful of what you pass in, however!

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.