我有一个MVC视图
- <%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage<ModelData>" %>
我有一个HTML标记的表单,用于一组复选框:
- <label for="MyCheckBox">Your choice</label>
- <input type="checkBox" id="Option1" class="checkBox" name="MyCheckBox" value="Option one" />
- <label for="Option1">Option one</label><br />
- <input type="checkBox" id="Option2" class="checkBox" name="MyCheckBox" value="Option two" />
- <label for="Option2">Option two</label><br />
我有一个控制器动作对
- class MyController : Controller {
- [AcceptVerbs(HttpVerbs.Post)]
- public ActionResult RequestStuff( ModelData data )
- {
- }
- }
并且在提交表单时调用该操作.
如何将复选框映射到ModelData的成员(以及我必须添加到ModelData的成员),以便在表单提交数据时存储哪些复选框被检查的信息?
解决方法
好的,这个是MVC3,但是 – 保存语法更改 – 也应该在MVC2中工作.这种做法基本上是一样的.
首先,你应该准备一个合适的(视图)模型
- public class Myviewmodel
- {
- [DisplayName("Option 1")]
- public bool Option1 { get; set; }
- [DisplayName("Option 2")]
- public bool Option2 { get; set; }
- }
然后,您将此模型传递给您显示的视图(控制器):
形式如下:
- @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)
- <p>
- <input type="submit" value="Submit"/>
- </p>
- }
现在这里的HTML帮助者(所有的CheckBoxFor,LabelFor,EditorFor等)允许将数据绑定到模型属性.
现在介意你,一个编辑器当属性是bool类型将给你在视图中的复选框.