@ Html.EditorFor () displays a DropDownList instead of a CheckBox

I am new to WebForms for MVC 3 and have a problem with the helper method @Html.EditorFor() .

I have a strongly typed view that represents data from a database, and one of the methods is of type bool? . I would like this to appear as a check box, but instead it appears as a drop-down list with the options "Not set", "True" and "False".

What is the easiest way to hide this up to the usual checkbox?

I understand that I can change the data type to a plain old bool , but this is a big EF object that I use, and it seems that you need to recreate the whole class just for that. I also understand that I’ll lose the ability to track the “not installed” state, but it’s more important for me to show a simple flag.

+8
asp.net-mvc asp.net-mvc-3 razor
source share
2 answers

Instead, use the helbox method, @ Html.CheckBoxFor () instead

This display of the drop-down list as a flag will not be able to provide the value "not set".

+9
source share

Basically, ASP.NET MVC has some default templates (you can read it here ).

If you want, you can add your own EditorTemplate, and ASP.NET MVC will use it instead of the standard one. To do this, you must put ~ / Views / ControllerName / EditorTemplates / or ~ / Views / Shared / EditorTemplates / in the file and // redefine it with your own functions.

Here is the default editor for Boolean, which can be enhanced by you:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <script runat="server"> private List<SelectListItem> TriStateValues { get { return new List<SelectListItem> { new SelectListItem { Text = "Not Set", Value = String.Empty, Selected = !Value.HasValue }, new SelectListItem { Text = "True", Value = "true", Selected = Value.HasValue && Value.Value }, new SelectListItem { Text = "False", Value = "false", Selected = Value.HasValue && !Value.Value }, }; } } private bool? Value { get { if (ViewData.Model == null) { return null; } return Convert.ToBoolean(ViewData.Model, System.Globalization.CultureInfo.InvariantCulture); } } </script> <% if (ViewData.ModelMetadata.IsNullableValueType) { %> <%= Html.DropDownList("", TriStateValues, new { @class = "list-box tri-state" }) %> <% } else { %> <%= Html.CheckBox("", Value ?? false, new { @class = "check-box" }) %> <% } %> 
+6
source share

All Articles