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

前端之家收集整理的这篇文章主要介绍了c# – 如何将复选框映射到MVC模型成员?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个MVC视图
  1. <%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage<ModelData>" %>

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

  1. <label for="MyCheckBox">Your choice</label>
  2. <input type="checkBox" id="Option1" class="checkBox" name="MyCheckBox" value="Option one" />
  3. <label for="Option1">Option one</label><br />
  4. <input type="checkBox" id="Option2" class="checkBox" name="MyCheckBox" value="Option two" />
  5. <label for="Option2">Option two</label><br />

我有一个控制器动作对

  1. class MyController : Controller {
  2. [AcceptVerbs(HttpVerbs.Post)]
  3. public ActionResult RequestStuff( ModelData data )
  4. {
  5. }
  6. }

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

如何将复选框映射到ModelData的成员(以及我必须添加到ModelData的成员),以便在表单提交数据时存储哪些复选框被检查的信息?

解决方法

好的,这个是MVC3,但是 – 保存语法更改 – 也应该在MVC2中工作.这种做法基本上是一样的.

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

  1. public class Myviewmodel
  2. {
  3. [DisplayName("Option 1")]
  4. public bool Option1 { get; set; }
  5.  
  6. [DisplayName("Option 2")]
  7. public bool Option2 { get; set; }
  8. }

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

  1. public ActionResult EditMyForm()
  2. {
  3. var viewmodel = new Myviewmodel()
  4. return View(viewmodel);
  5. }

形式如下:

  1. @model Myviewmodel
  2. @using( Html.BeginForm())
  3. {
  4. @Html.Label("Your choice")
  5.  
  6. @Html.LabelFor(model => model.Option1) // here the 'LabelFor' will show you the name you set with DisplayName attribute
  7. @Html.CheckBoxFor(model => model.Option1)
  8.  
  9. @Html.LabelFor(model => model.Option2)
  10. @Html.CheckBoxFor(model => model.Option2)
  11. <p>
  12. <input type="submit" value="Submit"/>
  13. </p>
  14. }

现在这里的HTML帮助者(所有的CheckBoxFor,LabelFor,EditorFor等)允许将数据绑定到模型属性.

现在介意你,一个编辑器当属性是bool类型将给你在视图中的复选框.

猜你在找的C#相关文章