Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC model boolean display yes or no

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?

like image 242
Marco Dinatsoli Avatar asked Dec 02 '13 21:12

Marco Dinatsoli


People also ask

What is display for in MVC?

Display modes in ASP.NET MVC 5 provide a way of separating page content from the way it is rendered on various devices, like web, mobile, iPhone, iPod and Windows Phones. All you need to do is to define a display mode for each device, or class of devices.

Can we create view without model in MVC?

If you don't want to create View Model then it is completely fine. You can loose some benefit like automatic client side validation ( data annotation). It means you have to do all validation by your self in client side and later on server side. This is simple way you can do that.

What is view in MVC with example?

In the Model-View-Controller (MVC) pattern, the view handles the app's data presentation and user interaction. A view is an HTML template with embedded Razor markup. Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client.

How many views does the model can have in MVC?

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible.


3 Answers

In your view:

@(item.isTrue?"Yes":"No") 
like image 183
Michael Dunlap Avatar answered Sep 24 '22 14:09

Michael Dunlap


You could use a custom html helper extension method like this:

@Html.YesNo(item.IsTrue)

Here is the code for this:

public static MvcHtmlString YesNo(this HtmlHelper htmlHelper, bool yesNo)
{
    var text = yesNo ? "Yes" : "No";
    return new MvcHtmlString(text);
}

This way you could re-use it throughout the site with a single line of Razor code.

like image 34
hutchonoid Avatar answered Sep 24 '22 14:09

hutchonoid


To expand on DigitalD's answer, you could consider wrapping this up in an extension method:

public static string ToFriendlyString(this Boolean b)
{
    return b ? "Yes" : "No";
}

Then you can use it all over the place:

@item.IsTrue.ToFriendlyString()
like image 23
Ant P Avatar answered Sep 23 '22 14:09

Ant P