i have a boolean field in my model in mvc 4 entity framework 4.5
i want to display the field in my view
i use this call
@item.isTrue
but i got true or false,
i want to get yes when true and no when false
what should i do please?
i have a boolean field in my model in mvc 4 entity framework 4.5
i want to display the field in my view
i use this call
@item.isTrue
but i got true or false,
what should i do please?
You could use a custom html helper extension method like this:
Here is the code for this:
This way you could re-use it throughout the site with a single line of Razor code.
There is a solution similar to @Lucas Niewohner's, taken from Scott on Writing .NET.
Create a DisplayTemplate called
YesNo.cshtml
:Then decorate the ViewModel with
UIHint
to wire it up:Now you can use your MVC helpers as usual:
You can take it one step further to create an EditorTemplate
YesNo.cshtml
as well:This approach is particularly helpful if you want to use the ViewModel in several places with a consistent implementation since you only have to associate the template in one place.
To expand on DigitalD's answer, you could consider wrapping this up in an extension method:
Then you can use it all over the place:
If you're in a rush, or you use an integer instead of bit. (I do this in case you have a third option later and your
yes/no
becomesyes, no, octopus
,as mine always seem to do, here is the simple plain quick dirty way of going... declare your variable at the top of the Razor view:As you go through your items...The following code will set your string variable
Active
to "Yes" or "No" and then you simply display it as is on the page (with no@Html.DisplayFor(...)
markup.In case you don't know already, surrounding the entire "if" Statement with
@{}
makes life easy - no@
's are needed within the brackets...This is a little late, but...
One useful method missed by other answers answers is the Custom DisplayTemplate method. By putting this Code:
Into a Partial View (Maybe
YesNo.cshtml
) in the Display Templates folder (/Views/Shared/DisplayTemplates
). Then, in your view, use this line:where "YesNo" is whatever you named your Partial View, minus the .cshtml extension.
By adding the second string (the
templateName
), you tell DisplayExtensions to display the boolean with your custom template, rather than the default method (a checkbox).This method may not be the simplest for this situation, but it comes in handy with more complex situations (such as, say, a custom calendar for selecting dates)
In your model write something like this:
Active is a boolean property, we create ISActive property for reading its value and show appropriate message to user.