Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override DisplayFor boolean?

Tags:

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)%> 
like image 228
newbie_86 Avatar asked Jul 29 '11 08:07

newbie_86


People also ask

What is DisplayFor?

DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.

What is DisplayFor MVC?

DisplayFor<TModel,TValue>(HtmlHelper<TModel>, Expression<Func<TModel,TValue>>, Object) Returns a string that contains each property value in the object that is represented by the specified expression, using additional view data. DisplayFor<TModel,TValue>(HtmlHelper<TModel>, Expression<Func<TModel,TValue>>)


1 Answers

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") 
like image 93
mateuscb Avatar answered Sep 18 '22 12:09

mateuscb