我有一个 MVC View
<%@ 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 />
我有一个 Controller - Action 对
class MyController : Controller {
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RequestStuff( ModelData data )
{
}
}
并且在提交表单时调用该操作。
如何将复选框映射到 ModelData
的成员(以及我必须将哪些成员添加到 ModelData
)以便在提交表单时 data
存储有关哪些复选框被选中的信息?
最佳答案
好的,这个将用于 MVC3,但是 - 除了语法更改 - 也应该在 MVC2 中工作。方法基本相同。
首先,你应该准备一个合适的( View )模型
public class MyViewModel
{
[DisplayName("Option 1")]
public bool Option1 { get; set; }
[DisplayName("Option 2")]
public bool Option2 { get; set; }
}
然后将此模型传递给显示的 View ( 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
等)允许将数据绑定(bind)到模型属性。
请注意,当属性的类型为 bool
时,EditorFor
也会在 View 中为您提供复选框。 :)
然后,当您提交给 Controller 时,它会自动绑定(bind)值:
[HttpPost]
public ActionResult EditMyForm(MyViewModel viewModel)
{
//And here the view model's items will be set to true/false, depending what you checked.
}
关于c# - 如何将复选框映射到 MVC 模型成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10649454/