发布到列表<modeltype> MVC3

Dan*_*nni 18 post list asp.net-mvc-3

我试图让我的视图将List发布回动作但是它一直以null为单位.

所以我的Model有一个WeightEntry对象列表.

运动模型

public class Exercise
{
    public List<WeightEntry> Entries { get; set; }
    public int ExerciseID { get; set; }
    public int ExerciseName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

WeightEntry模型

public class WeightEntry
{
    public int ID { get; set; }
    public int Weight { get; set; }
    public int Repetition { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的视图包含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" /> 
}
Run Code Online (Sandbox Code Playgroud)

控制器动作(Post)此刻什么都不做.我只是想在添加保存代码之前让绑定工作.

[HttpPost]
public ActionResult WeightEntry(Exercise exercise)
{
    try
    {
        //Add code here to save and check isvalid    
        return View(exercise);
    }
    catch
    {
        return View(exercise);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 40

替换以下循环:

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

有:

@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>
}
Run Code Online (Sandbox Code Playgroud)

甚至更好,使用编辑器模板并用以下代码替换循环:

@Html.EditorFor(x => x.Entries)
Run Code Online (Sandbox Code Playgroud)

然后定义一个自定义编辑器模板,该模板将自动为Entries集合的每个元素呈现(~/Views/Shared/EditorTemplates/WeightEntry.cshtml):

@model WeightEntry
<tr>
    <td>
        @Html.EditorFor(x => x.Repetition)
     </td>
     <td>
         @Html.EditorFor(x => x.Weight)
     </td>
 </tr>
Run Code Online (Sandbox Code Playgroud)

生成的输入元素将具有正确的名称,您将能够在POST操作中成功获取它们.

  • 神圣的废话 - 这确实有效.我在哪里送啤酒? (8认同)
  • @CodeBlend,查看生成的HTML中输入字段的`name`属性,并在两种情况下进行比较.然后阅读[`下面的文章`](http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx),你会明白为什么它适用于`for`和它不适用于`foreach`. (2认同)