gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:30:17 25 4
gpt4 key购买 nike

我正在尝试将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com