【问题标题】:MVC AJAX returns only partial viewMVC AJAX 仅返回部分视图
【发布时间】:2015-10-02 21:36:41
【问题描述】:

试图获取此 AJAX 表单以更新表的 tbody,但浏览器提交给控制器仅返回部分视图。我认为其他帖子中提到的所有 javascript 文件都被正确引用。以下代码来自一个测试应用程序,如果需要,可以转发。

当复选框被选中时,此表单应将表中的数据更改为 8 行而不是 4 行,但它不会更新表,只返回 8 行的局部视图的内容。

主视图(Index.cshtml):

@{
AjaxOptions options = new AjaxOptions
{
    UpdateTargetId = "notesTableBody",
    InsertionMode = InsertionMode.Replace
};
}

@using (Ajax.BeginForm("NotesPartial", options))
{
    <h3 class="csgOrange ib" style="margin-top:-20px;">Notes |</h3> <span class="f14">@Html.CheckBox("ShowMoreNotes") Show More Notes</span>
    <input type="hidden" id="num" name="num" value="8" />
}

<table class="table table-striped tableAutoWidth">
    <tr>
        <th>NoteID</th>
        <th>Title</th>
        <th>Text</th>
    </tr>
    <tbody id="notesTableBody">
        @Html.Action("NotesPartial", new { num = 4 })
    </tbody>

</table>

@section Scripts {

<script type="text/javascript">

    $(document).ready(function () {
        $('#ShowMoreNotes').click(function () {
            this.form.submit();
        });

    });

</script>

}

部分视图(NotesPartial.cshtml):

@model IEnumerable<TestAJAX.Models.NoteViewModel>
@foreach (TestAJAX.Models.NoteViewModel note in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => note.NoteID)</td>
        <td>@Html.DisplayFor(modelItem => note.Title)</td>
        <td>@Html.DisplayFor(modelItem => note.Text)</td>
    </tr>
}

表格内容控制器:

 public PartialViewResult NotesPartial(int num)
    {
        IList<NoteViewModel> noteList = new List<NoteViewModel>();

        for (int i=0; i<num; i++)
        {
            noteList.Add(new NoteViewModel { NoteID = i, Title = "Title " + i, Text = "Note text " + i });
        }

        return PartialView(noteList);
    }

javascript 文件引用在布局中处理。这是它们渲染后的样子。

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>

【问题讨论】:

  • 您在此处显示的脚本是正确的。你确定你没有在任何地方包含重复,并且在浏览器中启用了 javascript。

标签: jquery ajax asp.net-mvc-4


【解决方案1】:

想通了。它与提交表单的方式有关。我必须给 AJAX 表单一个 id:

@using (Ajax.BeginForm("NotesPartial", "Home", options, new { id = "NotesForm" }))

然后我可以通过这种方式提交表单:

$(document).ready(function () {
        $('#ShowMoreNotes').click(function () {
            //this.form.submit();
            $('#NotesForm').submit();
        });

    });

也许使用 this.form.submit() 不会将表单作为 AJAX 表单提交。

【讨论】:

  • this 是带有id="ShowMoreNotes" 的元素,即您的复选框,不包含表单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多