Create Label in ASP.Net MVC

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

We will use the following Student model class.

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

Html.LabelFor()

The Html.LabelFor<TModel,TProperty>() helper method is a strongly typed extension method. It generates a html label element for the model object property specified using a lambda 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 using a lambda expression in the LabelFor() method. The Display attribute on the StudentName property will be used as a label.

Label()

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

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>

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>
Want to check how much you know ASP.NET MVC?