c# - ASP.NET MVC 中的问题模型绑定(bind)嵌套列表

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

我正在尝试将 View 绑定(bind)到包含列表中的列表的模型。自然地,我更愿意使用开箱即用的模型绑定(bind)。昨天花了一些时间,我发现了一个真正的 hack 解决方法,我想纠正这个问题。我的模型的基本结构如下:

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;
}

View 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

但是,当我发布到 Controller 、设置断点并检查模型时,ScoreInfo 对象列表已被填充,但 ScoreInfo 对象内的 Category 对象列表尚未填充。

我的 Controller 中有以下 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");
        }
    }
}

最佳答案

您必须在类别类中使用属​​性而不是字段:

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

关于c# - ASP.NET MVC 中的问题模型绑定(bind)嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23795728/

相关文章:

c# - 延迟构建请求

C#:Regasm 为我的 COM DLL 中的每个类生成注册表项?

c# - WinForms Web 浏览器控件强制重新聚焦?

c# - Linq 查询中的 Select 操作何时变为投影操作?

.net - 以编程方式从 XSD 创建 XML 文件

c# - Paypal 立即购买按钮快速结帐

c# - 在遍历对象之前检查对象是否为空

c# - 如何动态地将接口(interface)​​放入泛型中?

c# - ForeignKeyConstraint.AcceptRejectRule 在 ADO.Net 中的用途?

javascript - 使用 Ajax 帮助程序与使用常规 html 和 jQuery 代码