加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:40:06 所属栏目:asp.Net 来源:网络整理
导读:我试图让我的观点发布一个列表回到行动,但它不断进入为空。 所以我的模型有一个WeightEntry对象列表。 运动模型 public class Exercise{ public ListWeightEntry Entries { get; set; } public int ExerciseID { get; set; } public int ExerciseName { get
我试图让我的观点发布一个列表回到行动,但它不断进入为空。

所以我的模型有一个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操作中成功获取它们。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读