Help with c# and bool on asp.net mvc

前端 未结 3 834
有刺的猬
有刺的猬 2021-01-04 20:47

Whats the best way to print out \"Yes\" or \"No\" depending on a value

In my view I want to print out

Model.isStudent

and I dont want True or False,

相关标签:
3条回答
  • 2021-01-04 21:24

    How about an extension method on bool:

    public static class BoolExtensions {
        public static string ToYesNo(this bool value) {
            return value ? "Yes": "No";
        }
    }
    

    Usage would be:

    Model.isStudent.ToYesNo();
    
    0 讨论(0)
  • 2021-01-04 21:27

    MVC 4: This example shows in detail the implementation of boolean templates for a dropdownlist that contains Yes, No and Not Set values and also handles null bool values. Inspired from Darin Dimitrov and Jorge - Thank you.

    Model Student.cs

    [Display(Name = "Present:")]
    [UIHint("YesNo")]
    public bool? IsPresent { get; set; }
    

    DisplayTemplates: YesNo.cshtml

    @model Nullable<bool>
    
    @if (Model.HasValue)
    {
        if (Model.Value)
            { <text>Yes</text> }
        else
            { <text>No</text> }
    }
    else
        { <text>Not Set</text> }
    

    EditorTemplates: YesNo.cshtml

    @model Nullable<bool>
    
    @{
        var listItems = new[]
        {   
            new SelectListItem { Value = "null", Text = "Not Set" },
            new SelectListItem { Value = "true", Text = "Yes" },
            new SelectListItem { Value = "false", Text = "No" }
        };  
    }
    
    @if (ViewData.ModelMetadata.IsNullableValueType)
    {
        @Html.DropDownList("", new SelectList(listItems, "Value", "Text", Model))
    }
    else
    {
        @Html.CheckBox("", Model.Value)
    }
    

    View:

      <div class="editor-label">
            @Html.LabelFor(model => model.IsPresent )
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.IsPresent )
            @Html.ValidationMessageFor(model => model.IsPresent )
        </div>
    
    0 讨论(0)
  • 2021-01-04 21:34

    Write a helper method:

    public static class MyExtensions
    {
        public static string FormatBool(this HtmlHelper html, bool value)
        {
            return html.Encode(value ? "Yes" : "No");
        }
    }
    

    And use it like this:

    <%= Html.FormatBool(Model.IsStudent) %>
    
    0 讨论(0)
提交回复
热议问题