我已经在你的模型中添加了一个 Selected
属性。
我已经添加了一个 EditorTemplate
来显示单个的 Field
。
现在当你提交时,所有项目都将被发送,然后你可以过滤出具有 Selected=true
属性的所有项目。
这个模型
public class TestModel
{
public IList<Field> Fields { get; set; }
}
public class Field
{
public String Key { get; set; }
public String Value { get; set; }
public bool Selected { get; set; }
}
控制器 [TestController.cs]
public ActionResult Index()
{
var testModel = new TestModel();
testModel.Fields = new List<Field>
{
new Field { Key = "Choice 1" , Selected = true , Value = "1"},
new Field { Key = "Choice 2" , Selected = false , Value = "2"},
new Field { Key = "Choice 3" , Selected = false , Value = "3"}
};
return View(testModel);
}
[HttpPost]
public ActionResult XY(TestModel model)
{
var selectedFields = model.Fields.Where(f => f.Selected);
return View();
}
视图 [/Views/Test/Index.cshtml]
@model MvcApplication2.Models.TestModel
@using(@Html.BeginForm("XY","Test"))
{
@Html.EditorFor(m => m.Fields)
<input type="submit" value="submit"/>
}
编辑器模板 [/Views/Test/EditorTemplates/Field.cshtml]
@model MvcApplication2.Models.Field
<label>
@Html.CheckBoxFor(m =>m.Selected)
@Model.Key
</label>
@Html.HiddenFor(m =>m.Value)
@Html.HiddenFor(m =>m.Key)