How do I override DisplayFor boolean?

谁都会走 提交于 2019-11-30 11:02:17

I had to create something similar so it would display "Sim" and "Não" (portuguese Yes/No). I created the following file:

 Views\Shared\DisplayTemplates\Boolean.ascx

And added the following code:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%= (bool) ViewData.Model ? "Sim" : "Não" %>

Hope this helps!

EDIT Forgot, in your view, simply call it like so:

<%= Html.DisplayFor(i => item.Ativo) %>

EDIT 2 For a nullable (bool?), try this:

<%= (ViewData.Model == null) ? "NA" : (ViewData.Model == true) ? "Y" : "N"%>

EDIT 3 Using Razor syntax (Views\Shared\DisplayTemplates\Boolean.cshtml):

 @{ Layout = null; }
 @(ViewData.Model ? "Sim" : "Não")

How about just this simple thing:

@((bool)item.Ativo ? "Yes" : "No")

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<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> 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.

Justin Grant

This is an old post, but I was having trouble finding a current answer.

There's actually an @HTML method in MVC 5, @Html.Display**Text**For(model => model.SomeBoolean).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!