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.
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.
@model Student
@Html.LabelFor(m => m.StudentName)
<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
@Html.Label("StudentName")
<label for="StudentName">Name</label>
You can specify another label text instead of property name as shown below.
@Html.Label("StudentName","Student Name")
<label for="StudentName">Student Name</label>