HtmlHelper - Label
Previously in the last tutorials, we learned how to use HtmlHelper methods to generate various form input elements. In this tutorial, we will learn how to create <label> element using HtmlHelper classes in the razor view of an ASP.NET MVC application.
To generate a <label> element, HtmlHelper class provides us with two extension methods:
- Label()
- LabelFor().
To illustrate the use of these two above methods, we will use the following Activities model as shown in the code snippet below:
//Demo: Activity Model
public class Activity
{
public int Id {get; set;}
public string ActivityName {get; set;}
public string Description {get; set;}
public string Status {get; set;}
}
Label()
The Html.Label() is a loosely typed method provided by the HtmlHelper class which generates a <label> element in razor view for the specified property of the model.
Label() method Signature: MvcHtmlString Label(string expression, string labelText, object htmlAttributes)Label() method has many overloads, just like every other method in the HtmlHelper class.
Example: Html.Display() in Razor View
@Html.Label("ActivityName")
Html Result:
<label for="ActivityName">Write C# Tutorial</label>
In the above example, we have specified an ActivityName property as a string. So, it will create an <label> element that displays the property name.
We can specify another label text instead of the default property name as shown in the code snippet below.
Example: Html.Label() in Razor View
@Html.Label("ActivityName","Activity-Name")
Html Result:
<label for="ActivityName">Activity-Name</label>
LabelFor
LabelFor helper method is a strongly typed extension method. It generates an Html label element for the model object property specified using a lambda expression.
LabelFor() method Signature: MvcHtmlString LabelFor(<Expression<Func<TModel,TValue>> expression)
Example: LabelFor() in Razor View
@model Activitiy
@Html.LabelFor(m => m.ActivityName)
Html Result:
<label for="ActivityName">Write C# Tutorial</label>
In the above code snippet, we have specified the ActivityName property of the Activity model using lambda expression in the LabelFor() method.
This expression generates <label> and set label text to the same as ActivityName property of the Activity model.
Inviting useful, relevant, well-written and unique guest posts
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework