6 Jun 2012

Override the ASP.NET MVC 3 Nullable Boolean EditorFor EditorTemplate

If you use EditorFor() in your MVC View code and pass it a nullable boolean (bool?), you'll see that MVC helpfully renders a tri-state dropdown list. However, the three choices in the dropdown are "Not Set", "True", and "False" which seem a bit unfriendly to some users.

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

4 comments:

  1. Many thanks for this tip

    ReplyDelete
  2. Great information, thanks. I have two small questions:

    1. 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!

    ReplyDelete
  3. Anonymous5:19 pm

    Thank you so much.
    I didn't found it on stack overflow either :)

    ReplyDelete
  4. Anonymous12:35 pm

    Thank you very much. Very helpful

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!