Ajax.BeginForm会在下拉列表的onchange事件中替换整个页面。

22

目的

我有一个简单的表格,列出了一些名字(在部分视图中),以及位于它上方的一个下拉列表,其中包含这些名字。目的是基于在下拉列表中选择的名称来过滤表格。过滤应该在选择的值更改时立即发生,并且应只重新呈现部分视图。

问题

当我在下拉列表中选择一个值时,部分视图不会在其他视图中呈现,而是显示为整个页面。 然而,当我在我的Ajax.BeginForm块中包括一个提交按钮,并在提交按钮上触发操作时,它会按预期功能...

代码

控制器

public PartialViewResult Filter(string filterName) {
    var names = from p in db.People
                select p;

    if (!String.IsNullOrEmpty(filterName))
    {
        names = names.Where(p => p.Name.Equals(filterName));
    }

    return PartialView("_PersonsTable", names);
}

视图

@model IEnumerable<Sandbox.Models.Person>

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Ajax.BeginForm("Filter", "Person", new AjaxOptions { 
    HttpMethod = "Get", UpdateTargetId = "SearchResults", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace }))
{
    @Html.DropDownList("filterName", new SelectList(ViewBag.Names), "Select a name", new   { onchange = "this.form.submit()" })
}

@Html.Partial("_PersonsTable")

局部视图

@model IEnumerable<Sandbox.Models.Person>

<table id="SearchResults">
    <tr>
        <th>
            Name
        </th>
        <th>
            Age
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}
</table>

为什么我的searchResults表格没有被呈现为部分视图?

我在我的_Layout视图中包含了这些脚本:

<script src="/Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
2个回答

36

在下拉菜单中替换:

new { onchange = "this.form.submit()" }

使用:

new { onchange = "$(this.form).submit();" }

同时移除所有的 MicrosoftAjax*.js 脚本。这些脚本已经完全过时了,不应该在 ASP.NET MVC 3 及更高版本的应用程序中使用。它们只是为了兼容性而提供,如果你正在从旧版本迁移,则可以使用。 jQuery.jsjquery.unobtrusive-ajax.js 就足够了。


2
这真的很愚蠢...我为此浪费了2个小时,哈哈。谢谢。 - sensei

0

不确定我是否理解正确,但如果提交按钮正常工作,为什么不这样做:

@Html.DropDownList("filterName", new SelectList(ViewBag.Names), "Select a name", new   { onchange = "clickMe('mybuttonId')" })

并编写小脚本

function clickMe(id) {
  $('#' + id).click() // where id is id of button that should submit the form.
}

如果您不想显示按钮,那么只需隐藏它。这是一种hack方法,如果不符合您的需求,我们可以进一步调查。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接