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

我试图让我的观点发布一个列表回到行动,但它不断进入为空。

所以我的模型有一个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; }
}

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

控制器动作(Post)目前什么都不做。在添加保存代码之前,我只是试图让绑定工作。

[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,而是整个列表为空,当我检查后,表单帖子。任何帮助是赞赏。
谢谢。

解决方法

替换以下循环:
@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操作中成功获取它们。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....