How do I override DisplayFor boolean?

newbie_86 picture newbie_86 · Jul 29, 2011 · Viewed 15k times · Source

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)%>

Answer

mateuscb picture mateuscb · Jul 29, 2011

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")