Save the following template as Boolean.cshtml under Views / Shared / EditorTemplates in your project and you'll see a more friendly widget by default.
@model bool? @using System.Web.Mvc @{ var selectList = new List<SelectListItem>(); selectList.Add(new SelectListItem { Text = "", Value = "" }); selectList.Add(new SelectListItem { Text = "Yes", Value = "true", Selected = Model.HasValue && Model.Value }); selectList.Add(new SelectListItem { Text = "No", Value = "false", Selected = Model.HasValue && !Model.Value }); } @Html.DropDownListFor(model => model, selectList)
Now you can customise it as you please.
If you don't want to override the standard template, bear in mind that you can save it with a different filename e.g. FriendlyBool.cshtml and then call it explicitly like so:
@Html.EditorFor(model => model.myNullableBool, "FriendlyBool")
Many thanks for this tip
ReplyDeleteGreat information, thanks. I have two small questions:
ReplyDelete1. How would you go about doing the same for "DisplayFor"?
2. Is there a way to do the same inside an ASP.NET MVC Webgrid?
Thanks!
Thank you so much.
ReplyDeleteI didn't found it on stack overflow either :)
Thank you very much. Very helpful
ReplyDelete