8

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 ?

1
  • Did you wrap it in script tags? Javascript won't be parsed unless wrapped Commented May 20, 2013 at 8:03

1 Answer 1

14

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 :)

Sign up to request clarification or add additional context in comments.

4 Comments

Really ? Let me tray, one more time.
Yes, absolutely ! Thank you.
@AlexPeta When i googled this question i thought that i found nothing but this is really interesting :) Thank You!!!
Can we put jquery in this script tag?

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.