Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing Yes/No instead of checkbox in the View of ASP.Net MVC

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,

like image 644
Ahmed Avatar asked Nov 28 '13 16:11

Ahmed


People also ask

Can you use ASPX pages in MVC yes or no?

If you add a plain ASPX page to an ASP.NET MVC project, well, it just works like a charm without any changes to the configuration. If you invoke the ASPX page, the ASPX page is processed with viewstate and postbacks.

How can get CheckBox value in ASP NET MVC?

Just add value="true" to the input tag. And use a hidden with value="false" as shown below.

What is DisplayFor MVC?

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.


2 Answers

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.

like image 146
hutchonoid Avatar answered Oct 11 '22 13:10

hutchonoid


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

 <td>
      @Html.Raw((Model.Staged)?"Yes":"No")     
 </td>
like image 34
Murali Murugesan Avatar answered Oct 11 '22 12:10

Murali Murugesan