发布到编辑控制器/视图

时间:2015-10-02 18:11:11

标签: c# asp.net-mvc asp.net-mvc-4

我有一个List<ReviewGroupViewModel>类型的模型,其中ReviewGroupViewModel是:

public class ReviewGroupViewModel
{
    public string Country { get; set; }
    public List<Review> Reviews { get; set; }
}

在我的Index.cshtml视图中,我使用嵌套的for循环遍历此模型,并为每个ReviewGroupViewModel构建一个表,按ReviewGroupViewModel.Country分组。我最终在每个Review对象的表格中都有一行。使用Commentary HTML帮助程序显示每行的TextAreaFor字段,允许用户输入文字:

Index.cshtml

@using (Html.BeginForm("Save", "Review", FormMethod.Post))
{
    for (var i = 0; i < Model.Count; i++)
    {
        <h6>@Html.DisplayFor(m => m[i].Country)</h6>
        <table class="table table-bordered table-condensed">
            <tr>
                <th style="text-align: center">
                    @Html.DisplayNameFor(m => m[i].Reviews[0].Commentary)
                </th>
                <th style="text-align: center">
                    Actions
                </th>
            </tr>
            @for (var j = 0; j < Model[i].Reviews.Count; j++)
            {
                <tr>
                    <td style="text-align: center">
                        @Html.TextAreaFor(m => m[i].Reviews[j].Commentary)
                    </td>
                    <td style="text-align: center">
                        @Html.ActionLink("Edit", "Edit", new { tempId = Model[i].Reviews[j].TempId }) |
                        @Html.ActionLink("Delete", "Delete", new { tempId = Model[i].Reviews[j].TempId })
                    </td>
                </tr>
            }
        </table>
    }
}

这是通过单击页面上其他位置的“保存”按钮提交的表单来限定的。

现在假设用户在索引视图中将一些文本键入一个(或多个)textareas,然后单击“Actions”中的“Edit”以获取给定的表行。然后这个文本丢失,因为我只是将Id(type:int)传递给我的Edit控制器方法。问题是,当导航到其他视图以进行编辑/删除等操作时,如何不丢失此输入文本(对于此Review对象和索引视图中的所有其他对象)?

AFAIK,您无法直接将复杂对象从视图传递到控制器方法。您显然也无法嵌套HTML表单。当然这是一个常见的场景,但我如何在代码中处理它?<​​/ p>

2 个答案:

答案 0 :(得分:0)

你的问题是ActionLink。它生成一个简单的超链接。超链接将向服务器发送GET请求。而且你不能把复杂的对象放在GET请求的主体中。

你需要这样做: Form with 2 submit buttons/actions

答案 1 :(得分:0)

您的&#39; for&#39;中的代码循环应该放在编辑器模板中。

@using (Html.BeginForm("Save", "Review", FormMethod.Post))
{
    for (var i = 0; i < Model.Count; i++)
    {
        @Html.EditorFor(m => Model[i], "MyTemplateName");
    }
}

在View文件夹中创建名为 EditorTemplates 的文件夹,并创建名为 MyTemplateName 的视图。在其中,您可以通过将单个模型传递给视图来获得迭代的每个单项的代码。

<强> MyTemplateName.cshtml

@model Review

<h6>@Html.DisplayFor(m => m.Country)</h6>
        <table class="table table-bordered table-condensed">
            <tr>
                <th style="text-align: center">
                    @Html.DisplayNameFor(m => m.Reviews[0].Commentary)
                </th>
                <th style="text-align: center">
                    Actions
                </th>
            </tr>
            @for (var j = 0; j < m.Reviews.Count; j++)
            {
                // Here you should have different editor template... see the pattern :)
                @Html.EditorFor(m => m.Reviews[j], "MySecondTemplate")
            }
        </table>

希望这些信息能为您提供帮助。