如何将复选框映射到MVC模型成员?

我有一个MVC视图

<%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage" %> 

我有一个带有HTML标记的表单,用于一组复选框:

   

我有一个控制器动作对

 class MyController : Controller { [AcceptVerbs(HttpVerbs.Post)] public ActionResult RequestStuff( ModelData data ) { } } 

并在提交表单时调用该操作。

如何将复选框映射到ModelData成员(以及我必须添加到ModelData成员),以便在提交表单时data存储有关选中复选框的信息?

好吧,这个将用于MVC3,但是 – 除了语法更改 – 也应该在MVC2中工作。 方法基本相同。

首先,您应该准备一个适当的(视图)模型

 public class MyViewModel { [DisplayName("Option 1")] public bool Option1 { get; set; } [DisplayName("Option 2")] public bool Option2 { get; set; } } 

然后将此模型传递给您正在显示的视图(控制器):

 public ActionResult EditMyForm() { var viewModel = new MyViewModel() return View(viewModel); } 

forms如下:

 @model MyViewModel @using( Html.BeginForm()) { @Html.Label("Your choice") @Html.LabelFor(model => model.Option1) // here the 'LabelFor' will show you the name you set with DisplayName attribute @Html.CheckBoxFor(model => model.Option1) @Html.LabelFor(model => model.Option2) @Html.CheckBoxFor(model => model.Option2) 

}

现在,HTML帮助程序(所有CheckBoxForLabelForEditorFor等)允许将数据绑定到模型属性。

现在请注意, EditorFor当属性类型为bool也会在视图中为您提供复选框。 🙂

然后,当您提交给控制器时,它将自动绑定值:

 [HttpPost] public ActionResult EditMyForm(MyViewModel viewModel) { //And here the view model's items will be set to true/false, depending what you checked. } 

首先,为选项定义SelectList 。 这将仅用于渲染复选框

  public IList OptionsSelectList { get; set; } 

比,你定义了一个会在post后保存单个选项的价值的模型

 public class ChooseOptionViewModel { public int OptionIdentifier { get; set; } //name or id public bool HasBeenChosen { get; set; } //this is mapped to checkbox } 

然后IList在ModelData的那些选项

 public IList Options { get; set; } 

最后,观点

  @for (int i = 0; i < Model.OptionsSelectList.Count(); i++) {   @Html.Hidden("Options[" + i + "].OptionIdentifier", Model.OptionsSelectList[i].Value)   @Model.OptionsSelectList[i].Text   @Html.CheckBox("Options[" + i + "].HasBeenChosen", Model.Options != null && Model.Options.Any(x => x.OptionIdentifier.ToString().Equals(Model.OptionsSelectList[i].Value) && x.HasBeenChosen))   } 

发布后,你只需检查Options.Where(x => x.HasBeenChosen)

这是全function的,它将允许您在validation错误发生时重新显示视图等。这看起来有点复杂,但我没有提出任何比这更好的解决方案。