如何绑定包含字典列表的视图模型?

时间:2014-06-26 19:24:16

标签: c# asp.net-mvc model-binding

我的ViewModel看起来像这样:

public class ParentViewModel
{
    public IList<ChildViewModel> Children { get; set; }
    public IList<AttributeViewModel> Attributes { get; set; }
}

public class ChildViewModel
{
    public IDictionary<int, bool> Attributes { get; set; }
}

public class AttributeViewModel
{
    public int AttributeId { get; set; }
    public string Description { get; set; }
}

相应的视图如下所示:

@for (var i = 0; i < Model.Children.Count; i++)
{
    for (var j = 0; j < Model.Attributes.Count; j++)
    {
        var attribute = Model.Attributes[j];
        @Html.DisplayFor(model => model.Attributes[j].Description)
        @Html.CheckBoxFor(model => model.Children[i].Attributes[attribute.AttributeId])
    }
}

当我尝试对我的控制器操作回发此视图时,我得到一个InvalidCastException。我在MVC中做的事情是什么?


供参考,这是我的相应控制器:

public class TestController : Controller
{
    public ActionResult Index()
    {
        return View("Index", new ParentViewModel
        {
            Attributes =
                new List<AttributeViewModel>
                {
                    new AttributeViewModel { AttributeId = 1, Description = "green" },
                    new AttributeViewModel { AttributeId = 2, Description = "spicy" }
                },
            Children = new[] { new ChildViewModel() }
        });
    }

    public ActionResult PostBack(ParentViewModel model)
    {
        // Does not work. Fails immediately
        return RedirectToAction("Index");
    }
}

我的观点:

@model ParentViewModel

@{
    Layout = null;
}

@using (Html.BeginForm("PostBack", "Test", FormMethod.Post))
{

    for (var i = 0; i < Model.Children.Count; i++)
     {
         for (var j = 0; j < Model.Attributes.Count; j++)
         {
             var attribute = Model.Attributes[j];
             @Html.DisplayFor(model => model.Attributes[j].Description)
             @Html.CheckBoxFor(model => model.Children[i].Attributes[attribute.AttributeId])
         }
     }
    <input type="submit"/>
}

1 个答案:

答案 0 :(得分:0)

如果这些是常规类而不是字典,我知道For循环和Razor语法看起来会有所不同。也许如果您尝试使用此语法对循环和东西进行建模,它将起作用。

 for (int i = 0; i < Model.listModel.Count; i++)
    {
          @Html.TextBoxFor(modelItem => Model.listModel[i].LastName)    

        for (int m = 0; m < Model.listModel[i].anotherListObj.Count; m++)
        {
              @Html.TextBoxFor(modelItem => Model.listModel[i].anotherListObj[m].FirstName)
        }
    }

编辑:

@Html.CheckBoxFor(model => model.Children[i].Attributes[attribute.AttributeId])    

上面看起来它试图将属性列表转换为属性字典

此外,我的循环语法适用于期望&#39; SomeModel&#39;和定义是这样的

SomeModel
{
  List<ListClass> listModel {get;set;}
}

ListCLass
{
  List<yetAnotherList> anotherListObj {get; set};
}