Search code examples
c#asp.net-mvcc#-4.0model-view-controllerhtml-helper

Inject Javascript Code along With HTML in MVC HTML Helper


I want to create a HTML Helper For a button and I want to inject some javascript(jQuery) code with that button to my page. How I can do this?

Thanks


Solution

  • Why don't you add a script in your htmlHelper? (of course you can add the scripts as parameters)

    public static class MyHtmlHelper
    {
        public static MvcHtmlString MyButton(this HtmlHelper helper,string text)
        {
            string script = @"<script> function MyMethod(){ alert('You clicked the button') ;} </script> ";
            StringBuilder html = new StringBuilder();
            html.AppendLine(script);
            html.AppendLine("<input type = 'submit' value = '"+ text + "' onclick='MyMethod()'");
            html.Append("/>");
            return new MvcHtmlString(html.ToString());
        }
    }
    

    and in your view

    @Html.MyButton("Click Me")