I read a lot of SO posts on how to define a template for @Html.DisplayFor for a boolean property, but couldn't understand them clearly. Your question is close to this, and after understanding it, I decided to add a new answer that includes all the steps for its implementation. This may be useful for other people.
1. Create a template
First you need to add a Partial View to the path below (the path is very important):
Views/Shared/DisplayTemplates/
For example, I created a Partial View named _ElementTemplate and _ElementTemplate it like this:
<span> @(@Model ? "Yes" : "No") </span>
2. Adding UIHint to the model
To establish the relationship between your property and template , you must add the UIHint attribute as UIHint below in your model class:
[UIHint("_YesOrNoTemplate")] public bool MyProperty { get; set; }
3. Using @ Html.DisplayNameFor in a View
Each time you view this property, you can use the following code:
<div> @Html.DisplayFor(modelItem => item.MyProperty) </div>
Exit
The above code is displayed in the following example ( if (MyProperty == true) ):
<div> <span> Yes </span> </div>
Attribute Settings
To set id or other HTML attributes you can use ModelMetadata as follows:
<span id="@ViewData.ModelMetadata.PropertyName"> @(@Model ? "Yes" : "No") </span>
Attribute Output
<div id="MyProperty"> <span> Yes </span> </div>
Ali Soltani Aug 13 '18 at 11:14 2018-08-13 11:14
source share