问题模型绑定ASP.NET MVC中的嵌套列表

时间:2014-05-21 23:57:25

标签: c# .net asp.net-mvc asp.net-mvc-4 razor

我正在尝试将视图绑定到包含列表中列表的模型。当然,我更喜欢使用开箱即用的模型绑定。昨天花了一些时间在上面我发现了一个非常黑客的解决方法,我想纠正这个问题。我的模型的基本结构如下:

public class MyMPIModel
{
    public List<ScoreInfo> ScoreInfo { get; set; }
}

public class ScoreInfo 
{
    public int ScorePrefId { get; set; }
    public List<Category> Categories { get; set; }
}

public class Category
{
    public int Id;
    public string Name;
    public bool Checked;
}

视图InterestCategories.cshtml包含以下格式:

@using (Html.BeginForm())
{
    for (var i = 0; i < Model.ScoreInfo.Count; i++)
    {
        @Html.EditorFor(x => x.ScoreInfo[i])
    }
}

编辑器模板ScoreInfo.cshtml:

@Html.HiddenFor(x => x.ScorePrefId)
<div class="preferences-block">
    @for (var i = 0; i < Model.Categories.Count; i++)
    {
        @Html.EditorFor(x => x.Categories[i])
    }
</div>

最后是编辑器模板Category.cshtml:

@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
<label>
    @Html.CheckBoxFor(x => x.Checked, new { @class = "check"})
    <span>@Model.Name</span>
</label>

使用firebug检查表单我可以看到所有隐藏的字段都已填充。此外,当我提交表格时,Fiddler会显示正确的数据。这是一个示例:

ScoreInfo[0].Categories[1].Id   2
ScoreInfo[0].Categories[1].Name Managing Money
ScoreInfo[0].Categories[1].Checked  false

但是,当我发布到控制器,设置断点并检查模型时,已填充ScoreInfo对象列表,但ScoreInfo对象内的Category对象列表没有。

我的控制器中有以下POST操作:

[HttpPost]
public ActionResult InterestCategories(MyMPIModel model, FormCollection form)
{
    ...

    //  model would not bind forcing me to populate via form collection
    for (var i = 0; i < model.ScoreInfo.Count; i++)
    {
        ...
        for (var j = 0; j < scoreInfo.Categories.Count; j++)
        {
                var category = scoreInfo.Categories[j];

                var prefix = "ScoreInfo[" + i + "].Categories[" + j + "]";

                category.Name = form[prefix + ".Name"];

                var sId = form[prefix + ".Id"];
                if (sId != null) category.Id = Int32.Parse(sId);

                var sChecked = form[prefix + ".Checked"];
                if (sChecked != null) category.Checked = sChecked.Contains("true");
        }
    }
}

1 个答案:

答案 0 :(得分:6)

您必须在Category类中使用Properties而不是Fields:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}