发布到列表<modeltype> MVC3 </modeltype>

时间:2012-02-16 05:54:38

标签: asp.net-mvc-3 list post

我试图让我的观点将List发布回动作,但它一直以null为主。

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

练习模型

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

WeightEntry模型

public class WeightEntry
{
    public int ID { get; set; }
    public int Weight { get; set; }
    public int Repetition { get; set; }
}

我的视图包含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" /> 
}

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

[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。任何帮助表示赞赏。 感谢。

1 个答案:

答案 0 :(得分:39)

替换以下循环:

@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操作中成功获取它们。

相关问题