Sunday, April 20, 2014

Razor HTML: For(model => model.x) vs DisplayFor(model => model.x)

I just wanted to highlight the difference in the function and formatting between the following:

@Html.xFor(model => model.x) vs.@Html.DisplayxFor(model => model.x)

Let's use an example where variable x = FirstName. I will describe the differences and usage of each below the HTML example.

@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName)
@Html.DisplayNameFor(model => model.FirstName)

Html.For makes actual labels here, in this case, for a form. It gives the textboxes and the value of FirstName.

@Html.DisplayNameFor(model => model.FirstName)
@Html.DisplayFor(model => model.FirstName)
@Html.DisplayFor(modelItem => item.FirstName)

Html.DisplayFor will render the DisplayTemplate (partial views inside the View folder of an MVC) that matches the property's type. So use it when you want to display a value from the view model.

Saturday, April 19, 2014