Create Label using HtmlHelper:

Learn how to create <label> element using HtmlHelper in razor view in this section.

HtmlHelper class includes two extension methods to generate html label : Label() and LabelFor().

We will use following Student model with to demo Label() and LabelFor() method.

Example: Student Model

public class Student
{
     public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public int Age { get; set; }
}

Label():

The Html.Label() method generates a <label> element for a specified property of model object.

Label() method Signature: MvcHtmlString Label(string expression, string labelText, object htmlAttributes)

Label() method has many overloads. Please visit MSDN to know all the overloads of Label() method

Example: Html.Label() in Razor View

@Html.Label("StudentName")

Html Result:

<label for="StudentName">Name</label>

In the above example, we have specified a StudentName property as a string. So, it will create <label> element that display Name.

You can specify another label text instead of property name as shown below.

Example: Html.Label() in Razor View

@Html.Label("StudentName","Student-Name")

Html Result:

<label for="StudentName">Student-Name</label>

LabelFor:

LabelFor helper method is a strongly typed extension method. It generates a html label element for the model object property specified using a lambda expression.

LabelFor() method Signature: MvcHtmlString LabelFor(<Expression<Func<TModel,TValue>> expression)

Visit MSDN to know all the overloads of LabelFor() method.

Example: LabelFor() in Razor View

@model Student

@Html.LabelFor(m => m.StudentName)

Html Result:

<label for="StudentName">Name</label>

In the above example, we have specified the StudentName property of Student model using lambda expression in the LabelFor() method. So, it generates <label> and set label text to the same as StudentName property name.