问题描述
我试图让我的视图将列表发布回操作,但它一直以空值出现.
I am trying to get my view to post a List back to the action however it keeps coming in as null.
所以我的模型有一个 WeightEntry 对象列表.
So my Model has a List of WeightEntry objects.
练习模型
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; }
}
我的视图包含运动名称和一个 WeightEntry 对象的循环
My View contains the ExerciseName and a forloop of WeightEntry objects
@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) 目前什么都不做.我只是想在添加保存代码之前让绑定工作.
The Controller Action (Post) Does nothing at the moment. I am just trying to get the binding working before I add the save code.
[HttpPost]
public ActionResult WeightEntry(Exercise exercise)
{
try
{
//Add code here to save and check isvalid
return View(exercise);
}
catch
{
return View(exercise);
}
}
我看到了一些向 MVC2 中使用的表单元素名称添加分子的小技巧,但我想知道 MVC3 是否有什么不同?我希望它能够很好地绑定 ID 为 0 或 null,但是当我在表单发布后检查它时,整个 List 为 null.任何帮助表示赞赏.谢谢.
I have seen a few little tricks with adding a numerator to the form elements' names used in MVC2 but I was wondering if MVC3 was any different? I was hoping it would all bind nicely with ID's being 0 or null but instead the whole List is null when I inspect it after the form posts. Any help is appreciated.Thanks.
推荐答案
替换如下循环:
@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>
}
或者更好的是,使用编辑器模板并将循环替换为:
or even better, use editor templates and replace the loop with:
@Html.EditorFor(x => x.Entries)
然后定义一个自定义编辑器模板,该模板将自动为 Entries 集合的每个元素呈现(~/Views/Shared/EditorTemplates/WeightEntry.cshtml
):
and then define a custom editor template that will automatically be rendered for each element of the Entries collection (~/Views/Shared/EditorTemplates/WeightEntry.cshtml
):
@model WeightEntry
<tr>
<td>
@Html.EditorFor(x => x.Repetition)
</td>
<td>
@Html.EditorFor(x => x.Weight)
</td>
</tr>
生成的输入元素将具有正确的名称,您将能够成功在您的 POST 操作中取回它们.
The the generated input elements will have correct names and you will be able to successfully fetch them back in your POST action.
这篇关于发布到列表<modeltype>MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!