Saturday 26 December 2020

HTML Helpers in MVC (5) Part 2

In this article we will focus on how to create custom Helper class. Lets create MVC5 application using visual studio 2019 community version

 

To create custom HTML helper in MVC, create static class CustomTextBox and static method TextBox inside class , method textbox is responsible to return string containing HTML syntax.  


Create action method inside user controller and view for the action method.


Add Custom helper in created view.

Run application to check custom textbox rendered properly on browser or not.


On browser custom textbox rendered as string and not textbox control. This is because in MVC all default helpers are HTML encoded. Right click on browser and select View Page source you observe custom textbox HTML string showing as ASCII string of HTML tags.


MVC also provide mechanism to solve this issue using Raw method and IHtmlString. 

1.      1.  @Html.Raw

2.      2. IHtmlString

      MVC accept HTML string as ACCII string of HTML and need to encode into HTML with the help of Raw methos or IHtmlStrings.

Let’s modify CustomeHelpers view by using Raw method and run application. 


Now Html rendered perfectly fine.

 

Another way to fix this issue is by using IHtmlString. All default (provided by MVC) helpers using IHtmlString interface to endcode  HTML string.

 

Modify CustomHtmlHelper class. You can also use MvcHtmlString instead of IHtmlString as return type. IHtmlString is base(Parent) for MvcHtmlstring.


Remove @Html.Raw() reference from View.


Run application and you can observer custom helper works as expected with IHtmlString interface.


Till now, we created custom helpers in separate class and MVC implement all helpers in @Html. In below screen custom helper called with @CustomTextBox and helpers provided by MVC framework called from @Html.


Can we create custom HTML helpers but called from @Html and not from @CustomTextBox?

Yes, we can do by using extension method concept, lets create custom helpers with extension method.


Observe Text method is now part of @Html, with the help of extension method we can extend library classes by adding methods to library classes.



For more information on Custom Helpers please visit official website of Microsoft from here

1 Comments:

At 26 December 2020 at 18:21 , Blogger Nihal Ahmed said...

Nice explained

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home