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 ?
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.
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.
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> .
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With