我如何映射到复选框MVC模式的成员? [英] How do I map checkboxes onto MVC model members?
问题描述
我有一个MVC视图
<%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage<ModelData>" %>
和我有HTML标记一组复选框的形式:
and I have a form with HTML markup for a set of checkboxes:
<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 />
和我有一个控制器操作对
and I have a controller-action pair
class MyController : Controller {
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RequestStuff( ModelData data )
{
}
}
当表单提交该操作将被调用。
and that action is invoked when the form is submitted.
我如何映射复选框上的成员 ModelData code>(什么会员我要加入
ModelData code>)这样,当表单提交
数据
存储在其复选框被选中的信息?
How do I map the checkboxes onto members of ModelData
(and what members I have to add to ModelData
) so that when the form is submitted data
stores information on which checkboxes are checked?
推荐答案
确定,这将是一个为MVC3,但 - 保存语法变化 - 应MVC2工作了。该方法基本上是相同的。
OK, this one will be for MVC3, but - save for syntax changes - should work in MVC2 too. The approach is essentially the same.
首先,你应该prepare合适的(视图)模型
First of all, you should prepare an appropriate (view)model
public class MyViewModel
{
[DisplayName("Option 1")]
public bool Option1 { get; set; }
[DisplayName("Option 2")]
public bool Option2 { get; set; }
}
然后你通过这个模型,你正在展示视图(控制器):
Then you pass this model to the view you're showing (controller):
public ActionResult EditMyForm()
{
var viewModel = new MyViewModel()
return View(viewModel);
}
与形式:
@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
等)允许将数据绑定到模型的属性。
Now here the HTML helpers (all the CheckBoxFor
, LabelFor
, EditorFor
etc) allow to bind the data to the model properties.
现在你要知道,一个 EditorFor
当地产的类型是布尔
会给你的复选框中视图,太。 :)
Now mind you, an EditorFor
when the property is of type bool
will give you the check-box in the view, too. :)
然后,当你提交到控制器,它会自动绑定值:
And then, when you submit to the controller, it will auto-bind the values:
[HttpPost]
public ActionResult EditMyForm(MyViewModel viewModel)
{
//And here the view model's items will be set to true/false, depending what you checked.
}
这篇关于我如何映射到复选框MVC模式的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!