SoftwareSavant
SoftwareSavant

Reputation: 9747

Displaying yes or no instead of 1 or 0 in MVC view

Is there a way I can annotate a field of my view so that it displays yes instead of one and no instead of 0 in my view? I know there is a display attribute that takes the name and displays something different, but that is not what I am looking for.

Upvotes: 0

Views: 2182

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

Create Display Template with name "YesNo"

@model int

@(Model == 0 ? "No" : "Yes")

And add attribute to field of your model

[UIHint("YesNo")]
public int Value { get; set; }

When you will display your model then "YesNo" display template will be used.

@Html.DisplayFor(model => model.Value) // output "Yes" or "No"

Upvotes: 4

jrummell
jrummell

Reputation: 43087

You have a few options. The simplest is to add some "display logic" in your View.

@(Model.YesNo == 1 ? "Yes" : "No")

I would create an Enum type and use it instead of an int on your model.

public enum YesNo
{
  No = 0,
  Yes, 1
}

Then your view would simply have

@Html.DisplayFor(model => model.YesNo)

Upvotes: 1

Related Questions