lame_coder
lame_coder

Reputation: 3115

Rendering Javascript via custom HTML Helper extension method?

In our ASP.NET MVC3 project we have written couple of custom HTML Helper extension method, which basically renders some composit controls (say a text and a label with some needed styles). Now we also want to render some javascript along with HTML tags, but looks MVCHtmlString does not render javascript test as javascript ! Any options or alternatives to render dynamic javascript from custom HTML Helpers ?

Upvotes: 8

Views: 12597

Answers (1)

Alex Peta
Alex Peta

Reputation: 1407

It works fine 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 the pop-up :)

Upvotes: 14

Related Questions