将值绑定到复杂类型

本文关键字:复杂 类型 绑定 | 更新日期: 2023-09-27 18:29:47

我有一个类似以下的模型:

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){[...]}

将值绑定到复杂类型

我已经为您的模型添加了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.chtml]

@model MvcApplication2.Models.Field
<label>
    @Html.CheckBoxFor(m =>m.Selected)
    @Model.Key 
</label>
@Html.HiddenFor(m =>m.Value)
@Html.HiddenFor(m =>m.Key)