Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering Javascript via custom HTML Helper extension method?

Tags:

asp.net-mvc

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 ?

like image 669
lame_coder Avatar asked May 20 '13 07:05

lame_coder


People also ask

What is HTML helper method?

An HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc.

What is custom HTML helper?

HTML Custom Helpers HTML helper is a method that returns a HTML string. Then this string is rendered in view. MVC provides many HTML helper methods. It also provides facility to create your own HTML helper methods. Once you create your helper method you can reuse it many times.

Can we create custom HTML helper?

Creating HTML Helpers with Static MethodsThe easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create a new HTML Helper that renders an HTML <label> tag. You can use the class in Listing 2 to render a <label> .

What is the difference between HTML helper and tag helpers?

HtmlHelpers vs. Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.


1 Answers

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

like image 127
Alex Peta Avatar answered Sep 21 '22 15:09

Alex Peta