I have written a basic HtmlHelper. Here's a test I wrote that simplifies what I was doing and to provide self assurance that it is happening when I use StringBuilder
and TagBuilder
objects:
public static string HelloWorld(this HtmlHelper htmlHelper, string name)
{
var sb = new StringBuilder();
var builder = new TagBuilder("span");
builder.InnerHtml = "Hello, " + name + "!";
sb.Append(builder.ToString(TagRenderMode.Normal));
sb.Append("<br/>");
return sb.ToString();
}
The output for this control encodes the string so I see the following:
<span>Hello, Jason!</span><br/>
In my view, I'm using the following: @Html.HelloWorld("Jason")
Any ideas what I can be doing wrong?
Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.
There are two ways in MVC to create custom Html helpers as below. We can create our own HTML helper by writing extension method for HTML helper class. These helpers are available to Helper property of class and you can use then just like inbuilt helpers. Add new class in MVC application and give it meaningful name.
What is Inline HTML Helper in MVC 5? Inline HTML Helper is used to create a reusable Helper method by using the Razor @helper tag. Inline helpers can be reused only on the same view. We can not use Inline helper to the different view Pages. We can create our own Inline helper method based on our requirements.
The Razor engine escapes HTML by default in any strings that it renders. If you change the return type to IHtmlString
, this won't happen.
public static IHtmlString HelloWorld(this HtmlHelper htmlHelper, string name)
...
return new HtmlString(sb.ToString());
}
Your static method must be HtmlString
instead of string
, and you must return the HtmlString(sb.ToString());
public static HtmlString HelloWorld(this HtmlHelper htmlHelper, string name)
{
var sb = new StringBuilder();
var builder = new TagBuilder("span");
builder.InnerHtml = "Hello, " + name + "!";
sb.Append(builder.ToString(TagRenderMode.Normal));
sb.Append("<br/>");
return new HtmlString(sb.ToString());
}
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