6

I am very new to ASP.Net / MVC . I have created a View that I am populating from a model. I am creating a rows for each item in the model to show their properties/attributes of model item.

One of the member is a bool , name is Staged. In the View I want to display it as Yes if true or No if false. The user will only be able to read it, so simple text Yes/No shall be sufficient.

I am using the following code in the cshtml

    <td>
        @Html.DisplayFor(modelItem => item.Staged)         
   </td>

This however shows a checkbox in the place, how can I show it as Yes/No ?

Thanks,

4 Answers 4

15

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

@Html.YesNo(item.Staged)

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Will this method be written in the view file ?
No, create a new static class within your project. I usually put them in an Extensions folder.
namespace System.Web.Mvc { public static class HtmlHelperExtensions { public static MvcHtmlString YesNo(this HtmlHelper htmlHelper, bool yesNo) { var text = yesNo ? "Yes" : "No"; return new MvcHtmlString(text); } } }
You need to change the namespace to this System.Web.Mvc instead of MvcApplication5.Extensions . Please accept when it works for you. :)
To call the helper class in your view you need to call it, for example at the top of your view you will add @using 'YourNamespace.ClassName
|
7

use Html.Raw and render the string conditionally based on model value true/false

 <td>
      @Html.Raw((Model.Staged)?"Yes":"No")     
 </td>

Comments

4

Change

    @Html.DisplayFor(modelItem => item.Staged)         

to

    @(item.Staged?"Yes":"No")         

This is the simplest way to achieve what your requirements.

2 Comments

In newer version of MVC 5 I used @(Model.myField?"Yes":"No"). The only change being "item" to "Model". And my field name.
If you are using @ model SomeNamespace.SomeModel then item will become Model, but in case @ model IEnumerable<somenamespace.somemodel> item will become the name of variable in the foreach loop. it is applicable on mvc 3+
3

In the model, you would need to make a new property that does something like this...

public string ItemStagedYesNo = (item.Staged) ? "Yes" : "No";

then in the view, do

@Html.DisplayFor(modelItem => ItemStagedYesNo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.