Using Razor, how do I make all “bool?” properties

2019-03-25 10:53发布

问题:

This question already has an answer here:

  • Help with c# and bool on asp.net mvc 3 answers

Here's my page code so far:

@model TennisClub.Models.ClubMember
@{
    ViewBag.Title = "Details";
}
<h2>
    Details
</h2>
<fieldset>
    <legend>ClubMember</legend>
    @Html.DisplayForModel()
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>

For all the nullable bools (bool?) in my model, this displays a dimmed select list with either Not Set, True, or False. I'd like it to be just plain text: either Not Set, Yes, or No.

How can I achieve this most easily? I'd like this style to be global throughout my site.

Edit

Just took a stab at making a template per Mark's answer, but the details page looks exactly the same.

I created a bool.cshtml file and placed it in the following folder:

[ProjectFolder]/Views/Shared/DisplayTemplates

Here's what I have for my bool.cshtml template at the moment:

@model bool?

@if (Model == null)
{
    <text>Not Set</text>
}
else
{
    if (Model.Value)
    {
        <text>Yes</text>
    }
    else
    {
        <text>No</text>
    }
}

This doesn't seem to have any affect on my details pages at all.

Any idea what I'm doing wrong?

Edit 2

Here's my model class:

public class ClubMember
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string PhoneNumber { get; set; }
    public string PhoneType { get; set; }
    public bool? CanPlayDays { get; set; }
    public bool? CanPlayEvenings { get; set; }
    public bool? CanPlayWeekends { get; set; }
    public string Role { get; set; }
}

回答1:

You would want to override the default template. In short, under your views folder, you would create a "DisplayTemplates" folder and a "EditorTemplates" folder. Once you have this, you can create a Boolean.cshtml file in each one where the Model is bool?. Then you can do what ever you want as far as display options go. This will change how all bool? model fields render.

Here is a blog post that I have refered to many times to help me figure this out. http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html

UPDATE: One word of caution, remember to handle the null case. I have forgotten to do that in the past and it had bitten me.



回答2:

The template file is the way to go for site wide implementation. But I'd take it a step further with an extension method.

public static string ToString(this bool? b, string ifTrue, string ifFalse, string ifNull)
{
   if(!b.HasValue) return ifNull;
   return b.Value ? ifTrue : ifFalse;
}
Boolean.ToString("Yes","No","Not Set");

This allows easier display of arbitrary values.