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

前端 未结 6 1315
小蘑菇
小蘑菇 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:33

    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:

    
        @(@Model ? "Yes" : "No")
    
    

    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:

    @Html.DisplayFor(modelItem => item.MyProperty)

    Output

    The code above is rendered to code below in my example (if (MyProperty == true)):

    Yes

    Setting attributes

    For setting id or other html attributes you can use ModelMetadata like this:

    
        @(@Model ? "Yes" : "No")
    
    

    Output with attribute

    Yes

提交回复
热议问题