When should I use Html.Displayfor in MVC

后端 未结 2 1730
一生所求
一生所求 2020-11-27 06:02

I am new to MVC and know how to use Html.Displayfor(), but I don\'t know when to use it?

Any idea?

相关标签:
2条回答
  • 2020-11-27 06:15

    I'm extending @Darin's answer.

    Html.DisplayFor(model => model.SomeCollection) will iterate over items in SomeCollection and display the items using DisplayFor() recursively.

    0 讨论(0)
  • 2020-11-27 06:26

    The DisplayFor helper renders the corresponding display template for the given type. For example, you should use it with collection properties or if you wanted to somehow personalize this template. When used with a collection property, the corresponding template will automatically be rendered for each element of the collection.

    Here's how it works:

    @Html.DisplayFor(x => x.SomeProperty)
    

    will render the default template for the given type. For example, if you have decorated your view model property with some formatting options, it will respect those options:

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

    In your view, when you use the DisplayFor helper, it will render the property by taking into account this format whereas if you used simply @Model.SomeProperty, it wouldn't respect this custom format.

    but don't know when to use it?

    Always use it when you want to display a value from your view model. Always use:

    @Html.DisplayFor(x => x.SomeProperty)
    

    instead of:

    @Model.SomeProperty
    
    0 讨论(0)
提交回复
热议问题