我已經添加到您的模型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);
/** Do some logic **/
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)