asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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操作中成功获取它们。

大佬总结

以上是大佬教程为你收集整理的asp.net-mvc-3 – 发布到列表MVC3全部内容,希望文章能够帮你解决asp.net-mvc-3 – 发布到列表MVC3所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。