How do I create a MVC Razor template for DisplayFor()

前端 未结 6 1317
小蘑菇
小蘑菇 2020-12-03 03:07

I have a couple of properties in my view model that are display-only but I need to retrieve their values using jQuery to perform a calculation on the page. The standard

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 03:20

    OK, I found it and it's actually very simple. In my Views\Shared\DisplayTemplates folder I have Reading.cshtml containing the following:

    @model System.Int32
    @Model
    

    This renders the correct tag using the name of the property as the id attribute and the value of the property as the contents:

    1234
    

    In the view file this can be called using the following:

    @Html.DisplayFor(model => model.Reading, "Reading")
    

    Or if the model property is decorated with UIHint("Reading") then the template name can be left out of the call to DisplayFor() and it will still render using the template:

    @Html.DisplayFor(model => model.Reading)
    

    This should work equally well with custom editor templates.

提交回复
热议问题