MVC AJAX仅返回部分视图

时间:2015-10-02 21:36:42

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

尝试获取此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>

1 个答案:

答案 0 :(得分:1)

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

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

    });

然后我就能以这种方式提交表格:

UPDATE UserKarma SET karma = karma + 1 where user_id = d9d9354a-32e9-46d7-a56c61e21b486ae3 and sub_type = 'test';

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

相关问题