How do I create a MVC Razor template for DisplayFor()
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
<span id="@ViewData.ModelMetadata.PropertyName">@Model</span>
This renders the correct tag using the name of the property as the id attribute and the value of the property as the contents:
<span id="Reading">1234</span>
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.
I read many SO posts about defining template for @Html.DisplayFor
for Boolean property but I couldn't clearly understand them. Your question is closed to this and after grasping it, I decided to add a new answer including all steps needed for implementing that. It might be helpful for other people.
1. Creating a template
At first, you need to add a Partial View
in path below (the path is very important):
Views/Shared/DisplayTemplates/
For example, I created a Partial View
that named _ElementTemplate
and Fill it like this:
<span>
@(@Model ? "Yes" : "No")
</span>
2. Adding UIHint to the Model
To make a connection between your property
and template
, you should add UIHint
attribute like below in your model class:
[UIHint("_YesOrNoTemplate")]
public bool MyProperty { get; set; }
3. Using @Html.DisplayNameFor in View
In every view that you need this property, you can use code below:
<div>
@Html.DisplayFor(modelItem => item.MyProperty)
</div>
Output
The code above is rendered to code below in my example (if (MyProperty == true)
):
<div>
<span>
Yes
</span>
</div>
Setting attributes
For setting id
or other html attributes you can use ModelMetadata like this:
<span id="@ViewData.ModelMetadata.PropertyName">
@(@Model ? "Yes" : "No")
</span>
Output with attribute
<div id="MyProperty">
<span>
Yes
</span>
</div>