Search code examples
asp.net-mvc-3booleancheckboxdisplay-templates

How do I override DisplayFor boolean?


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

Solution

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