将值绑定到复杂类型

5

我有一个如下的模型:

public class TestModel{
    public IList<Field> Fields {get; set;}
}

public class Field{
    public String Key {get; set;}
    public String Value {get; set;}
}

如何制作相应的视图表单,以便在提交请求后正确绑定模型?用户应该能够通过复选框选择各种字段,并且模型应包含所选字段。在下面的Action方法中,模型成员为空。

public ActionResult XY(TestModel model){[...]}
1个回答

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接