1

Rendering a list of objects into HTML in Razor Pages I found two options. Are these the same?

Using model property directly

<tbody>
    @foreach (var item in Model.ResumeList)
    {
        <tr>
            <td>@item.DeviceID</td>
        </tr>
    }
</tbody>

vs using Html.DisplayFor

<tbody>
    @foreach (var item in Model.ResumeList)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.DeviceID)</td>
        </tr>
    }
</tbody>

If not, what is the functional advantage of one over the other?

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
Megrez7
  • 1,423
  • 1
  • 15
  • 35

1 Answers1

2

The DisplayFor helper renders the corresponding display template for the given type.If you don't add custom format,the results of Html.DisplayFor and property directly will be the same.

If you add custom format,Html.DisplayFor,it will respect the custom format,and property directly will not.Here is a demo:

public class Test {
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime SomeProperty { get; set; }
    }

view:

<div>
    @Html.DisplayFor(model => model.SomeProperty)
</div>
<div>
    @Model.SomeProperty
</div>

result:

enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22