2010-02-03 34 views
8

Whats cách tốt nhất để in ra "Có" hoặc "Không" tùy thuộc vào giá trịTrợ giúp với C# và bool trên asp.net MVC

Theo quan điểm của tôi, tôi muốn in ra

Model.isStudent

và tôi không muốn Đúng hay Sai, tôi muốn Có hoặc Không .... tôi có phải viết nếu tuyên bố khác không?

Trả lời

11

Viết một phương pháp helper:

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

Và sử dụng nó như thế này:

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

Làm thế nào về một phương pháp mở rộng trên bool:

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

Cách sử dụng sẽ là:

Model.isStudent.ToYesNo(); 
2

MVC 4: Ví dụ này cho thấy chi tiết việc triển khai các mẫu boolean cho danh sách thả xuống có chứa giá trị Có, Không và Không được đặt và cũng xử lý các giá trị bool null. Lấy cảm hứng từ Darin Dimitrov và Jorge - Cảm ơn bạn.

Mẫu 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) 
} 

Xem:

<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> 
Các vấn đề liên quan