C# 如何将复选框映射到 MVC 模型成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10649454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I map checkboxes onto MVC model members?
提问by sharptooth
I have an MVC view
我有一个 MVC 视图
<%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage<ModelData>" %>
and I have a form with HTML markup for a set of checkboxes:
我有一个带有 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 />
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.
并且在提交表单时调用该操作。
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 datastores information on which checkboxes are checked?
如何将复选框映射到成员ModelData(以及我必须添加到的成员ModelData),以便在提交表单时data存储有关哪些复选框被选中的信息?
采纳答案by Patryk ?wiek
OK, this one will be for MVC3, but - save for syntax changes - should work in MVC2 too. The approach is essentially the same.
好的,这将用于 MVC3,但是 - 除了语法更改之外 - 也应该在 MVC2 中工作。方法基本相同。
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);
}
with the form:
与形式:
@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>
}
Now here the HTML helpers (all the CheckBoxFor, LabelFor, EditorForetc) allow to bind the data to the model properties.
现在,这里的HTML佣工(所有的CheckBoxFor,LabelFor,EditorFor等),允许绑定到数据模型的属性。
Now mind you, an EditorForwhen the property is of type boolwill give you the check-box in the view, too. :)
现在请注意,EditorFor当属性为 type 时,bool也会在视图中为您提供复选框。:)
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.
}
回答by archil
First you define SelectListfor Options. This will be used just to render checkboxes
首先定义SelectList选项。这将仅用于呈现复选框
public IList<SelectListItem> OptionsSelectList { get; set; }
Than, you define model that will hold value of single chosen option after post
然后,您定义模型,该模型将在发布后保存单个选定选项的值
public class ChooseOptionViewModel
{
public int OptionIdentifier { get; set; } //name or id
public bool HasBeenChosen { get; set; } //this is mapped to checkbox
}
Then IList of those options in ModelData
然后 IList 中的这些选项 ModelData
public IList<ChooseOptionViewModel> Options { get; set; }
And finally, the view
最后,视图
@for (int i = 0; i < Model.OptionsSelectList.Count(); i++)
{
<tr>
<td class="hidden">
@Html.Hidden("Options[" + i + "].OptionIdentifier", Model.OptionsSelectList[i].Value)
</td>
<td>
@Model.OptionsSelectList[i].Text
</td>
<td>
@Html.CheckBox("Options[" + i + "].HasBeenChosen", Model.Options != null && Model.Options.Any(x => x.OptionIdentifier.ToString().Equals(Model.OptionsSelectList[i].Value) && x.HasBeenChosen))
</td>
</tr>
}
After post, you just inspect Options.Where(x => x.HasBeenChosen)
发布后,您只需检查 Options.Where(x => x.HasBeenChosen)
This is full-functional, and it will allow you to redisplay view when validation errors occur, etc. This seems a bit complicated, but I haven't come up with any better solution than this.
这是全功能的,它允许您在发生验证错误等时重新显示视图。这看起来有点复杂,但我还没有想出比这更好的解决方案。

