How do I override DisplayFor boolean?

后端 未结 5 1118
醉话见心
醉话见心 2021-01-01 12:36

How do i create a display template so i can display a bool as Yes or No not a checkbox? Using mvc3

<%: Html.DisplayFor(model => model.SomeBoolean)%>         


        
5条回答
  •  时光说笑
    2021-01-01 13:15

    For true/false use DisplayTextFor by Justin Grant

    For yup/nope based on Nuri YILMAZ, this is .NetCore 2.2, to downgrade replace HtmlString with MvcHtmlString:

    1) C# write new extension DisplayForYZ

    public namespace X.Views.Shared
    {
        public static class DisplayExtensions
        {
            // If this was called DisplayFor not DisplayForYZ, we'd get recursion
            public static IHtmlContent DisplayForYZ
              (this HtmlHelper html, Expression> expression) 
            where TModel : Y
            {
                object o = expression.Compile().Invoke(html.ViewData.Model);
                // For any bool on TModel, return in this custom way:
                if (o.GetType() == typeof(bool))
                {
                    return (bool)o ? new HtmlString("Yup") : new HtmlString("Nope");
                }
                // Otherwise use default behaviour 
                return html.DisplayFor(expression);
            }
        }
    }
    

    2) cshtml: Import the DisplayExtensions namespace and use new extension.

    @model X.ViewModels.Y
    @using X.Views.Shared;
    
    @Html.DisplayForYZ(modelItem => modelItem.Z)   @*//Yup/Nope*@
    @Html.DisplayForYZ(modelItem => modelItem.A)   @*//default non bool behavior*@
    
    @Html.DisplayFor(modelItem => modelItem.Z)     @*//check box*@
    @Html.DisplayTextFor(modelItem => modelItem.Z) @*//true/false*@
    

    X = {my company} Y = {object for customised display} Z= {bool property} A= {non-bool property}

提交回复
热议问题