上下文:MVC3,JQuery
大家好!我试图通过键入文本框来过滤webgrid,问题是,当使用Ajax.BeginForm时,整个布局在webgrid应该是重复的位置。
这是相同的这里的问题jquery.unobtrusive-ajax.min causing strange behavior on the view
控制器
[HttpPost] [ChildActionOnly] public ViewResult Files(string filePath) { IEnumerable<File> results = repository.FindBy(f => f.Path.StartsWith(filePath)).Take(5); return View("_grid", results); }
@model IEnumerable<DAL.File>
@{
Layout = null;
}
@{var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10, ajaxUpdateContainerId: "myGrid");
grid.Pager(WebGridPagerModes.NextPrevious);
@grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Path", "File"),
grid.Column("Size", "Size (bytes)", canSort: true),
grid.Column("User", "Owner")
))}
@model IEnumerable<DAL.File> @{ Layout = null; } @using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "myGrid" })) { @Html.TextBox("filePath", null, new { onKeyUp = "$('form').submit()" }) } div id="myGrid"> @Html.Partial("_grid", Model) /div
感谢您的帮助,我真的需要它:)
答案 0 :(得分:0)
我的代码似乎有一些问题,我第一眼就看到了:
jQuery.js
和jquery.unobtrusive-ajax.js
所需的脚本Files
控制器操作使用[ChildActionOnly]
属性进行修饰,这意味着无法通过Ajax调用访问它我尝试过一点清理你的代码并提供一个例子:
public class HomeController : Controller
{
public ActionResult Index()
{
var files = IEnumerable<File> results = repository.FindAll();
return View(files);
}
[HttpPost]
public ActionResult Index(string filePath)
{
var files = repository.FindBy(f => f.Path.StartsWith(filePath)).Take(5);
return View("_grid", files);
}
}
然后您可以拥有相应的Index.cshtml
视图:
@model IEnumerable<DAL.File>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
@using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "myGrid" }))
{
@Html.TextBox("filePath", null, new { onkeyup = "$('form').submit()" })
}
<div id="myGrid">
@Html.Partial("_grid", Model)
</div>
和_grid.cshtml
部分:
@model IEnumerable<DAL.File>
@{
Layout = null;
}
@{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10, ajaxUpdateContainerId: "myGrid");
grid.Pager(WebGridPagerModes.NextPrevious);
@grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Path", "File"),
grid.Column("Size", "Size (bytes)", canSort: true),
grid.Column("User", "Owner")
)
)
}
另请注意,每当用户在文本框中键入一些键时,使用AJAX请求来篡改服务器是一个非常糟糕的主意。