ASP.NET MVC 5 Ajax 搜索功能返回部分视图,但不返回搜索结果 [英] ASP.NET MVC 5 Ajax search function returns partial view, but not the search results
问题描述
我正在研究由搜索字符串文本框中的 onkeydown 事件触发的 ajax 搜索功能.只要您在文本框中输入内容,它就会立即在局部视图中仅返回与搜索字符串匹配的类别.
服务器端的搜索功能按照我想要的方式工作,它根据结果将视图模型列表返回给视图.但是,视图看起来完全没有变化.
下面是我在文本框中完全不输入任何内容的索引视图:
但是当我以这种方式输入搜索字符串时,应该只显示Hats",它看起来像这样:
这是我需要解决的问题.
这是相关的控制器代码:
public ActionResult SearchCategories(string searchString){var allCategories = _repository.GetAll().ToList();var 结果 = allCategories.Where(c => c.Name.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Name).ToList();列表categoryViewModels = new List();foreach(结果中的类别 c){CategoryViewModel 模型 = 新 CategoryViewModel {Id = c.Id, Name = c.Name, Parent = c.Parent };categoryViewModels.Add(model);}var categoryParents = new List();foreach(结果属于 c 类){if (c.Parent != null){类别 parentCategory = _repository.GetById(c.Parent.Value);categoryParents.Add(parentCategory);}}foreach (categoryViewModel 模型在 categoryViewModels){if (model.Parent != null){model.ParentName = categoryParents.Where(c => c.Id == model.Parent.Value).First().Name;}}return PartialView("PartialSearchResult", categoryViewModels);}
Index.cshtml:
@using GUI.Models@model IEnumerable@{ViewBag.Title = "索引";}<h2>类别</h2><p>@Html.ActionLink((HttpUtility.HtmlDecode(" «") + " Back to Admin Page"), "Index", "Admin", null, new { @class = "btn btn-primary btn-large"}) |@Html.ActionLink("Create New Category" + (HttpUtility.HtmlDecode(" »")), "Create", "Category", null, new { @class = "btn btn-primary btn-large" })</p><div id="indexTable"><table class="table"><tr><th>@Html.DisplayNameFor(model => model.Name)</th><th>@Html.DisplayName("父")</th><th>@using (Ajax.BeginForm("SearchCategories", "Category", new AjaxOptions { UpdateTargetId = "target" })){<div class="form-group">@Html.TextBox("searchString", "", new { onkeydown = "searchCategories();", onkeyup = "searchCategories();", onkeypress = "searchCategories();" })<input type="submit" value="Search" class="btn btn-default"/>
}</th></tr>@if(模型!= null){foreach(模型中的 CategoryViewModel 项){<tr><td>@Html.DisplayFor(modelItem => item.Name)</td><td>@if(item.Parent != null){@Html.DisplayFor(modelItem => item.ParentName)}</td><td>@if (item.Parent != null){@Html.ActionLink("Edit", "Edit", new {id = item.Id})如果(User.Identity.IsAuthenticated){if(User.IsInRole("Admin")){<强>|</strong>@Html.ActionLink("Delete", "Delete", new {id = item.Id})}}}</td></tr>}}
<小时/>@section 脚本 {@Scripts.Render("~/bundles/jquery","~/bundles/jqueryajax")<script type="text/javascript">功能搜索类别(){var searchWord = $('#searchString').val();$.ajax({url: '/Category/SearchCategories?searchString=' + searchWord,类型:'获取',成功:功能(数据){警报('Koppling');}});}
请注意,此 javascript 函数对控制器进行了 ajax 调用:
function searchCategories() {var searchWord = $('#searchString').val();$.ajax({url: '/Category/SearchCategories?searchString=' + searchWord,类型:'获取',成功:功能(数据){警报('Koppling');}});}
我想用来返回搜索结果的部分视图:
@model IEnumerable<div id="目标"><table class="table">@foreach(模型中的变量项目){<tr><td>@Html.DisplayFor(modelItem => item.Name)</td><td>@if (item.Parent != null){@Html.DisplayFor(modelItem => item.ParentName)}</td><td>@if (item.Parent != null){@Html.ActionLink("Edit", "Edit", new { id = item.Id })如果(User.Identity.IsAuthenticated){如果(User.IsInRole(管理员")){<strong>|</strong>@Html.ActionLink("删除", "删除", new { id = item.Id })}}}</td></tr>}
@section 脚本 {@Scripts.Render("~/bundles/jquery","~/bundles/jqueryajax")}
我还注意到,ajax 请求的状态代码为200 OK".那么我该如何解决这个问题?
尝试在控制器中重命名:
public ActionResult SearchCategories(string searchString)
进入这个:
public PartialViewResult SearchCategories(string searchString)
在你的视图中使用这个:
也不要忘记在这段代码前加上 jquery.unobtrusive-ajax.js
@using (Ajax.BeginForm("SearchCategories", "Home",new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" })){<h3>搜索:</h3>@Html.TextBox("searchString", null, new { id = "Search" })<input type="submit" value="Search" class="btn btn-primary"/>}<div id="搜索结果"></div>
希望能帮到你
I'm working on an ajax search functionality triggered by a onkeydown event in the searchstring textbox. As soon as you enter something in the textbox, it' suppose to return only the categories that match the searchstring immidiately in a partial view.
Search function on the server side works just the way I want, and it returns the list of viewmodels based on the result back to the view. However, the view looks totally unchanged.
Below is the index View where I entered absolutely nothing in the textbox:
But when I enter the searchstring in such a way, that only "Hats" should be displayed, it looks like this:
This is my problem that I need to fix.
Here's the relevant controller code:
public ActionResult SearchCategories(string searchString)
{
var allCategories = _repository.GetAll().ToList();
var result = allCategories.Where(c => c.Name.StartsWith(searchString, StringComparison.OrdinalIgnoreCase))
.OrderBy(x => x.Name).ToList();
List<CategoryViewModel> categoryViewModels = new List<CategoryViewModel>();
foreach (Category c in result)
{
CategoryViewModel model = new CategoryViewModel { Id = c.Id, Name = c.Name, Parent = c.Parent };
categoryViewModels.Add(model);
}
var categoryParents = new List<Category>();
foreach (Category c in result)
{
if (c.Parent != null)
{
Category parentCategory = _repository.GetById(c.Parent.Value);
categoryParents.Add(parentCategory);
}
}
foreach (CategoryViewModel model in categoryViewModels)
{
if (model.Parent != null)
{
model.ParentName = categoryParents.Where(c => c.Id == model.Parent.Value).First().Name;
}
}
return PartialView("PartialSearchResult", categoryViewModels);
}
The Index.cshtml:
@using GUI.Models
@model IEnumerable<GUI.Models.CategoryViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Categories</h2>
<p>
@Html.ActionLink((HttpUtility.HtmlDecode(" «") + " Back to Admin Page"), "Index", "Admin", null, new { @class = "btn btn-primary btn-large" }) |
@Html.ActionLink("Create New Category" + (HttpUtility.HtmlDecode(" »")), "Create", "Category", null, new { @class = "btn btn-primary btn-large" })
</p>
<div id="indexTable">
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayName("Parent")
</th>
<th>
@using (Ajax.BeginForm("SearchCategories", "Category", new AjaxOptions { UpdateTargetId = "target" }))
{
<div class="form-group">
@Html.TextBox("searchString", "", new { onkeydown = "searchCategories();", onkeyup = "searchCategories();", onkeypress = "searchCategories();" })
<input type="submit" value="Search" class="btn btn-default" />
</div>
}
</th>
</tr>
@if (Model != null)
{
foreach (CategoryViewModel item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@if(item.Parent != null)
{
@Html.DisplayFor(modelItem => item.ParentName)
}
</td>
<td>
@if (item.Parent != null)
{
@Html.ActionLink("Edit", "Edit", new {id = item.Id})
if(User.Identity.IsAuthenticated)
{
if(User.IsInRole("Admin"))
{
<strong> | </strong>@Html.ActionLink("Delete", "Delete", new {id = item.Id})
}
}
}
</td>
</tr>
}
}
</table>
</div>
<hr />
@section Scripts {
@Scripts.Render("~/bundles/jquery",
"~/bundles/jqueryajax")
<script type="text/javascript">
function searchCategories() {
var searchWord = $('#searchString').val();
$.ajax({
url: '/Category/SearchCategories?searchString=' + searchWord,
type: 'GET',
sucess: function (data) {
alert('Koppling');
}
});
}
Note that this javascript function makes the ajax call to the controller:
function searchCategories() {
var searchWord = $('#searchString').val();
$.ajax({
url: '/Category/SearchCategories?searchString=' + searchWord,
type: 'GET',
sucess: function (data) {
alert('Koppling');
}
});
}
The partial View I want to use to return the search results:
@model IEnumerable<GUI.Models.CategoryViewModel>
<div id="target">
<table class="table">
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@if (item.Parent != null)
{
@Html.DisplayFor(modelItem => item.ParentName)
}
</td>
<td>
@if (item.Parent != null)
{
@Html.ActionLink("Edit", "Edit", new { id = item.Id })
if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Admin"))
{
<strong>|</strong>@Html.ActionLink("Delete", "Delete", new { id = item.Id })
}
}
}
</td>
</tr>
}
</table>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jquery",
"~/bundles/jqueryajax")
}
I've also noticed, that the ajax request got the status code "200 OK". So how do I solve this?
Try to rename this in controller:
public ActionResult SearchCategories(string searchString)
into this:
public PartialViewResult SearchCategories(string searchString)
in your View use this:
also don't forget to put jquery.unobtrusive-ajax.js before this code
@using (Ajax.BeginForm("SearchCategories", "Home",
new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" }))
{
<h3>Search:</h3>
@Html.TextBox("searchString", null, new { id = "Search" })
<input type="submit" value="Search" class="btn btn-primary" />
}
<div id="searchResults"></div>
hope this helps
这篇关于ASP.NET MVC 5 Ajax 搜索功能返回部分视图,但不返回搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!