raranibar
raranibar

Reputation: 1267

JavaScript into StringBuilder

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

Upvotes: 2

Views: 1154

Answers (2)

bhamlin
bhamlin

Reputation: 5187

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!

Upvotes: 1

Travis J
Travis J

Reputation: 82287

I would suggest wrapping this in Html.Raw

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

Upvotes: 1

Related Questions