gpt4 book ai didi

asp.net-mvc-3 - 发布到列表 MVC3

转载 作者:行者123 更新时间:2023-12-03 13:20:24 27 4
gpt4 key购买 nike

我试图让我的观点将列表发布回操作,但它一直为空。

所以我的模型有一个 WeightEntry 对象列表。

运动模型

public class Exercise
{
public List<WeightEntry> Entries { get; set; }
public int ExerciseID { get; set; }
public int ExerciseName { get; set; }
}

权重模型
public class WeightEntry
{
public int ID { get; set; }
public int Weight { get; set; }
public int Repetition { get; set; }
}

我的 View 包含ExerciseName 和WeightEntry 对象的forloop
@model Mymvc.ViewModels.Exercise
...
<span>@Model.ExerciseName</span>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<table class="left weight-record">
<tr>
<th>Reps</th>
<th>Weight</th>
</tr>
@foreach (var item in Model.Entries)
{
<tr>
<td>
@Html.EditorFor(x => item.Repetition)
</td>
<td>
@Html.EditorFor(x => item.Weight)
</td>
</tr>
}
</table>
<input type="submit" value="Save" />
}

Controller Action (Post) 目前什么都不做。我只是想在添加保存代码之前让绑定(bind)工作。
[HttpPost]
public ActionResult WeightEntry(Exercise exercise)
{
try
{
//Add code here to save and check isvalid
return View(exercise);
}
catch
{
return View(exercise);
}
}

我已经看到了一些在 MVC2 中使用的表单元素名称中添加分子的小技巧,但我想知道 MVC3 是否有任何不同?我希望它能够很好地绑定(bind) ID 为 0 或 null,但是当我在表单发布后检查它时,整个 List 为 null。任何帮助表示赞赏。
谢谢。

最佳答案

替换以下循环:

@foreach (var item in Model.Entries)
{
<tr>
<td>
@Html.EditorFor(x => item.Repetition)
</td>
<td>
@Html.EditorFor(x => item.Weight)
</td>
</tr>
}

和:
@for (var i = 0; i < Model.Entries.Count; i++)
{
<tr>
<td>
@Html.EditorFor(x => x.Entries[i].Repetition)
</td>
<td>
@Html.EditorFor(x => x.Entries[i].Weight)
</td>
</tr>
}

甚至更好的是,使用编辑器模板并将循环替换为:
@Html.EditorFor(x => x.Entries)

然后定义一个自定义编辑器模板,该模板将自动为 Entries 集合的每个元素呈现 ( ~/Views/Shared/EditorTemplates/WeightEntry.cshtml):
@model WeightEntry
<tr>
<td>
@Html.EditorFor(x => x.Repetition)
</td>
<td>
@Html.EditorFor(x => x.Weight)
</td>
</tr>

生成的输入元素将有 correct names并且您将能够在您的 POST 操作中成功取回它们。

关于asp.net-mvc-3 - 发布到列表<modeltype> MVC3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9306246/

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