I want to know exactly when to use @Html.DisplayFor
and when to use @Html.LabelFor
in MVC.
Everytime I work on them, it confuses me.
DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.
DisplayFor displays the value for the model item and DisplayNameFor simply displays the name of the property?
Answers. Label was introduced MVC 1 used in view templates. LabelFor was introduced in MVC2 is for "support strongly-typed HTML helpers that use lambda expressions when referencing models/viewmodels passed to a view template.
The <label> HTML element represents a caption for an item in a user interface.
suppose you have a property model like this:
[Display("Name:")]
public string Name{get;set;}
and you need to show in your view like this:
Name: Mohammad
then you can do this:
@HTML.LabelFor(m=>m.Name)// this will show "Name:"
@Html.DisplayFor(m=m>m.Name)// this will show (read only) "Mohammad"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With