I understand that in Razor, @Html does a bunch of neat things, like generate HTML for links, inputs, etc.
But I don’t get the DisplayFor function…
Why would I write:
@Html.DisplayFor(model => model.Title)
when I could just write:
@Model.Title
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Html.DisplayFor()will render the DisplayTemplate that matches the property’s type.If it can’t find any, I suppose it invokes
.ToString().If you don’t know about display templates, they’re partial views that can be put in a
DisplayTemplatesfolder inside the view folder associated to a controller.Example:
If you create a view named
String.cshtmlinside theDisplayTemplatesfolder of your views folder (e.gHome, orShared) with the following code:Then
@Html.DisplayFor(model => model.Title)(assuming thatTitleis a string) will use the template and display<strong>Null string</strong>if the string is null, or empty.