Posted on 3/26/2020 9:59:40 AM by Admin

Html Helpers in Asp.Net MVC

In Asp.Net Webform we had server controls available for faster development. Similarly in Asp.Net MVC we have Html Helpers which can be used for faster development ,But unlike server controls they don't have ViewState and Events ,so is lightweight.

Below are the important points we developer should know about Html Helpers:-

1. Asp.Net MVC provides two types of built-in Html Helpers:-
  • Standard Html Helpers.
  • Strongly Typed Html Helpers.

2. We can create our own Html Helpers.

3. All Html Helpers return MVCHtmlString.

Let us discuss all the points one by one:-

Standard Html Helpers:-

As i have already said Html helpers are for faster development and the sole purpose of Standard Html helpers is exactly the same.So it is completely up to you ,whether you use Pure Html or Html Helpers in your project.

Html Helpers are nothing but extension methods defined in HtmlHelper class,Which can be accessed with @Html in razor view,Where Html is an object of HtmlHelper class and @ symbol is used to access server side object in razor view.

Below are the Standard Html Helpers available in Asp.Net MVC .

HtmlHelper Html Control
Html.TextBox Textbox
Html.TextArea TextArea
Html.CheckBox Checkbox
Html.RadioButton Radio button
Html.DropDownList Dropdown
Html.ListBox multi-select/Listbox
Html.Hidden Hidden field
Html.Password Password textbox
Html.Display Html text
Html.Label Label
Html.Editor

It is a bit different and generates Html controls based on
the dataType of specified model property as the editor name.
Like Numeric for int,Textbox for string and DateTime input for DateTime
ie even it is not strongly typed and accept model property name as string
as editor name.You will always need model in your view.
so its better to use Html.EditorFor.

Html.ActionLink Anchor tag (Action Link)

Lets understand it by creating a Login Form.


@using (Html.BeginForm("SaveStudent", "Studen", FormMethod.Post))
{
    <table>
        <tr>
            <td>@Html.Label("UserName")</td>
            <td>@Html.TextBox("txtUserName")</td>
        </tr>
        <tr>
            <td>@Html.Label("Password")</td>
            <td>@Html.Password("txtPassword")</td>
        </tr>
        <tr>
            <td>@Html.Label("Remember Me")</td>
            <td>@Html.CheckBox("IsPersistant")</td>
        </tr>
        <tr>

            <td colspan="2"><button type="submit">Login</button></td>
        </tr>
    </table>
}

As you can see, For User Name i have used Html.Textbox,for Password Html.Password ,for Remember me Html.Checkbox and for Label Html.Label.Similary you can use any Html helper as per your requirement.

Strongly Typed Html Helpers:-

As the name suggests here your html helpers will be strongly typed meaning binded with your model property, so it is less error prone.

We have below Strongly Typed Html Helpers available in Asp.Net MVC.

HtmlHelper Html Control
Html.TextBoxFor Textbox
Html.TextAreaFor TextArea
Html.CheckBoxFor Checkbox
Html.RadioButtonFor Radio button
Html.DropDownListFor Dropdown
Html.ListBoxFor multi-select/Listbox
Html.HiddenFor Hidden field
Html.PasswordFor Password textbox
Html.DisplayFor Html text
Html.LabelFor Label
Html.EditorFor

It is a bit different and generates Html controls based on
the dataType of specified model property as the editor name.
Like Numeric for int,Textbox for string and DateTime input for DateTime

Each strongly Typed Extension method that is Html Helper accept Expression <Func<TModel,TValue> > as parameter

meaning expression of type Func.If you have gone through my CSharp articles then you should know func is a readymade delegate which can accept any method with signature of any return type and parameters.In support of delegate we have Lambda expression which helps us to write inline delegates and we do not need to create external methods .Lambda expression is actually short way of creating methods Where left side of => symbol represents method argument(parameter) and right side of => symbol represents method body.

For Html Helpers the Func is designed to automatically take model as method argument(input) and it will return any value as output.

so if i am writing @Html.TextboxFor(m=>m.Id) .it means it is an extension method which is asking for Func,Func is expecting any method with model as input and any output.I am simply passing my model as input and returning one of its property as output ,in current case Id.

So,it will generate a Textbox with Name="Id" .

Using strongly typed html helpers have following advantages over pure Html:-
  1. Faster development .
  2. Easy for sending data from view to controller and model binding.
  3. Easier for client side validation with data annotation.

Lets understand each point with same example of Login Form.

First create a model class and name it as Student as shown below.


  public class Student
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool IsPersistant { get; set; }
    }

Now Replace the view with below code.


  @using MVCExample.Models
  @model Student
  @using (Html.BeginForm("SaveStudent", "Studen", FormMethod.Post))
   {
    <table>
        <tr>
            <td>@Html.LabelFor(l => l.UserName)</td>
            <td>@Html.TextBoxFor(m => m.UserName)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(l => l.Password)</td>
            <td>@Html.PasswordFor(m => m.Password)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(l => l.IsPersistant)</td>
            <td>@Html.CheckBoxFor(m => m.IsPersistant)</td>
        </tr>
        <tr>

            <td colspan="2"> <button type="submit">Login</button></td>
        </tr>
    </table>
  }

As you can observe first i have imported the model namespace in view and made the view strongly typed with student model.

I have used the strongly Typed version of Html Helpers and passed lambda expression with Student model as input and desired property as output as it accepts Func delegate.

Now you can judge that apart from faster development ,it is less error prone as we are bound to use model and it's property.Hence first point is justified.

Also as we have used model property in each html helper so it will generate related html control with exact same name as the name of the property.Meaning ,we will no longer need to create custom model binder and Action method will catch every property with their value correctly.So here Second Point is also justified.

The Third Point can not be justified right now ,and we will discuss it in the Next arcticle.

Create Custom Html Helper:-

Inline Html Helper

Creating Custom Html Helper in the same view is called as inline Html Helper. Obviously it can only be used in the current view only.

To create inline html helper we need to define method with @helper tag in razor view.


 @helper BookList(string[] books)
    {
    <ul>

        foreach(var book in books){
        <li><strong>@book</strong></li>
        }
    </ul>

    }
  @BookList(new string[] { "Book1", "Book2", "Book3" })

It will Give the below output.

Inline Html Helper
Inline Html Helper

Now ,Look closely and try to understand why the response is in list with bold font.The answer is MVCHtmlString.Actually all Html helper return MVCHtmlString,meaning the string which is already encoded and does not need further encoding.

External Html Helper with Extension Method:-

An extension method is a custom external method which acts as an instance method for any class or Type.

For example we have Length method defined in String class.So whenever we put dot (.) after any string ,the intellisense shows as the Length method,but if we want our own method under string class to act in the same way meaning to act like an instance method we need to extend string type.

similary if we want the intellisence to show our own method on putting dot after Html tag we will have to extend HtmlHelper class(Type).

To make an extension method we need three things:-
  1. Make your class static
  2. Make the method static
  3. Mark the(class) type with this prefix, which you want to extend.

Lets modify the BookList inline html helper and convert it into extension method so that it can be used in any view.


   public static MvcHtmlString BookList(this HtmlHelper html, string Book)
     {

       return  MvcHtmlString.Create(
@"
<li>"+"<b>"+Book+"</b>"+"</li>"

                    );
     }

Now you can use this method as an instance method of HtmlHelper class,with @Html tag in your view like below.


   @{
    string[] books = { "Book1", "Book2", "Book3" };
    }
  @foreach (var item in books)
  {
    <ul>
        @Html.BookList(item)
    </ul>
  }

You will get the same result as eariler.