目的
我有一个简单的表列出名称(部分视图),并在其上方包含这些名称的下拉列表。目的是根据在下拉列表中选择的名称过滤表格。一旦下拉列表中的选定值发生变化,就应该进行过滤,并且只应再次渲染部分视图。
问题
当我在下拉列表中选择一个值时,部分视图不会在另一个视图中呈现,而是显示为整个页面。
但是,当我在我的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>
在你的下拉列表中替换:
new { onchange = "this.form.submit()" }
有:
new { onchange = "$(this.form).submit();" }
还要摆脱所有的MicrosoftAjax * .js脚本。这些是完全遗产的,不应该在ASP.NET MVC 3和更新的应用程序中使用。仅当您从旧版本迁移时,才会出于兼容性原因提供它们。 jQuery.js和jquery.unobtrusive-ajax.js就够了。