Rendering Javascript through native HTML helper extension method?

In our ASP.NET MVC3 project, we wrote a couple of special HTML Helper extension methods that basically create some compositing controls (like text and shortcut with some necessary styles). Now we also want to display some javascript along with HTML tags, but it looks like MVCHtmlString does not display the javascript test like javascript! Any options or alternatives for rendering dynamic javascript from custom HTML helpers?

+7
source share
1 answer

This works great for me :)

Here is what I used as an extension method:

namespace MvcApplication1.ExtensionMethods { public static class MyExtensionMethods { public static MvcHtmlString SomeJavascript(this HtmlHelper helper) { StringBuilder sb = new StringBuilder(); sb.Append("<script> alert('testing 123')</script>"); return MvcHtmlString.Create(sb.ToString()); } } } 

and in my index.cshtml I call it like this:

 @using MvcApplication1.ExtensionMethods .... @Html.SomeJavascript() 

and it shows me a popup :)

+11
source

All Articles