开发者

Help with c# and bool on asp.net mvc

开发者 https://www.devze.com 2022-12-18 19:20 出处:网络
Whats the best way to print out \"Yes\" or \"No\" depending on a value In my view I want to print out Model.isS开发者_开发知识库tudent

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

In my view I want to print out

Model.isS开发者_开发知识库tudent

and I dont want True or False, I want Yes or No.... do I Have to write if else statement?


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) %>


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();


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

精彩评论

暂无评论...
验证码 换一张
取 消