Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Html.DisplayFor boolean checkbox MVC

I have a boolean property IsActive. In the view is a list of objects with their properties (including IsActive). But in the list the IsActive is a non-editable checkbox since it's boolean. If I change DisplayFor() to DisplayTextFor() then it will just display True or false instead of checkbox. How can I change True and false to 'Active' and 'Inactive' where Active is true and Inactive is false?

      @Html.DisplayTextFor(modelItem => item.IsActive) 

And then I would style the 'Active' to green and 'Inactive' to red

like image 371
TMan Avatar asked Mar 22 '12 01:03

TMan


3 Answers

You can use a display template to format the way your property is displayed.

Create a DisplayTemplates folder either under ~/Shared or in the View folder where the view that will be using this template exists.

Add a new partial view to this folder. Name it anything you'd like, e.g. IsActive.cshtml

@model bool
@if (Model == true)
{
    @Html.Encode("Active")
}
@if (Model == false)
{
    @Html.Encode("Inactive")
}

Now add data annotation to your property to let it know to use this display template.

[UIHint("IsActive")]
public bool IsActive { get; set; }

Use Html.DisplayFor on any bool with this annotation and it will be formatted according to the display template with the matching name. With some tweaking, you can place the color change style directly in your display template.

like image 73
nightshifted Avatar answered Nov 19 '22 06:11

nightshifted


This is a old question, but this might help someone. I had the exact same problem and solved with @(IsFooBar ? "Yes" : "No").

like image 31
E-Magno Avatar answered Nov 19 '22 07:11

E-Magno


You can try this:

@if (item.IsActive) 
{ 
    @string.Format("Active");
}
else
{ 
    @string.Format("Inactive");
}
like image 3
Swamy Avatar answered Nov 19 '22 05:11

Swamy