Help with c# and bool on asp.net mvc

前端 未结 3 849
有刺的猬
有刺的猬 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条回答
  •  Happy的楠姐
    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
    
    @if (Model.HasValue)
    {
        if (Model.Value)
            { Yes }
        else
            { No }
    }
    else
        { Not Set }
    

    EditorTemplates: YesNo.cshtml

    @model Nullable
    
    @{
        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:

      
    @Html.LabelFor(model => model.IsPresent )
    @Html.EditorFor(model => model.IsPresent ) @Html.ValidationMessageFor(model => model.IsPresent )

提交回复
热议问题