2010-02-03 70 views

回答

11

写一个辅助方法:

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

而且使用这样的:

<%= Html.FormatBool(Model.IsStudent) %> 
6

如何在布尔扩展方法:

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

用法是:

Model.isStudent.ToYesNo(); 
2

MVC 4:此示例详细显示了包含Yes,No和Not Set值并且还处理null布尔值的下拉列表的布尔模板的实现。受到Darin Dimitrov和Jorge的启发 - 谢谢。

型号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) 
} 

查看:

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