Changing Html.DisplayFor boolean checkbox MVC

前端 未结 4 1087
生来不讨喜
生来不讨喜 2021-02-12 07:30

I have a boolean property IsActive. In the view is a list of objects with their properties (including IsActive). But in the list the IsActive is a non-editable checkbox since it

相关标签:
4条回答
  • 2021-02-12 07:49

    You can use a display template to format the way your property is displayed.

    Create a DisplayTemplates folder either under ~/Shared or in the View folder where the view that will be using this template exists.

    Add a new partial view to this folder. Name it anything you'd like, e.g. IsActive.cshtml

    @model bool
    @if (Model == true)
    {
        @Html.Encode("Active")
    }
    @if (Model == false)
    {
        @Html.Encode("Inactive")
    }
    

    Now add data annotation to your property to let it know to use this display template.

    [UIHint("IsActive")]
    public bool IsActive { get; set; }
    

    Use Html.DisplayFor on any bool with this annotation and it will be formatted according to the display template with the matching name. With some tweaking, you can place the color change style directly in your display template.

    0 讨论(0)
  • 2021-02-12 07:51

    I'd like to complement nightshifted's solution so that it works well with localized string as well. Also, using @Html.Encode() strings with special characters are encoded wrong. For example "Kyllä" (Finnish for Yes) gets encoded badly. That is why there is no @Html.Encode() at all in my solution.

    This solution assumes that you are using localization with SharedResources approach (refer ASP.NET Core Localization with help of SharedResources)

    @using Microsoft.AspNetCore.Mvc.Localization
    @model bool
    @inject IHtmlLocalizer<SharedResources> L
    
    @if (Model)
    {
        @L["Yes"]
    }
    else
    {
        @L["No"]
    }
    
    0 讨论(0)
  • 2021-02-12 08:01

    This is a old question, but this might help someone. I had the exact same problem and solved with @(IsFooBar ? "Yes" : "No").

    0 讨论(0)
  • 2021-02-12 08:02

    You can try this:

    @if (item.IsActive) 
    { 
        @string.Format("Active");
    }
    else
    { 
        @string.Format("Inactive");
    }
    
    0 讨论(0)
提交回复
热议问题