我有一个类似下面的模型:
public class TestModel{
public IList<Field> Fields {get; set;}
}
public class Field{
public String Key {get; set;}
public String Value {get; set;}
}
我如何制作相应的视图表单,以便在发布请求后正确绑定模型?用户应该能够选中具有复选框的各个字段,并且模型应该包含所选的字段。 在下面的Action方法中,Model的成员为null。
public ActionResult XY(TestModel model){[...]}
答案 0 :(得分:3)
我已在您的模型中添加了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)