How do I override DisplayFor boolean?

后端 未结 5 1126
醉话见心
醉话见心 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:24

    you can extend HtmlHelper for bool.

    and remember you must use direction YesNoExtensions namespace on razor page . rem:we can overload DisplayFor for boolean with change function sign.

    public namespace SampleExtensions
    {
        public static class YesNoExtensions
        {
            public static MvcHtmlString DisplayFor(this HtmlHelper html, Expression> expression, bool flag = true)
            {
                object o = expression.Compile().Invoke(html.ViewData.Model);
                if (o.GetType() == typeof(bool))
                {
                    if ((bool)o)
                        return new MvcHtmlString("Yes");
                    else
                        return new MvcHtmlString("No");
                }
                return DisplayFor(html, expression);
            }
        }
    }
    

    and razor page.

    <%@ import namespace='SampleExtensions' %>
    
    
    <%: Html.DisplayFor(model => model.SomeBoolean, true)%>
    

    last parameter true is dummy for select right DisplayFor which has been overload by us. I hope usefull.

提交回复
热议问题