【问题标题】:ASP.NET MVC 5 Ajax search function returns partial view, but not the search resultsASP.NET MVC 5 Ajax 搜索功能返回部分视图,但不返回搜索结果
【发布时间】:2014-04-18 13:32:01
【问题描述】:

我正在研究由搜索字符串文本框中的 onkeydown 事件触发的 ajax 搜索功能。只要您在文本框中输入内容,它就会在部分视图中立即返回与搜索字符串匹配的类别。

服务器端的搜索功能按我想要的方式工作,它会根据结果将视图模型列表返回给视图。但是,视图看起来完全没有变化。

下面是我在文本框中完全没有输入任何内容的索引视图:

但是当我以这种方式输入搜索字符串时,应该只显示“帽子”,它看起来像这样:

这是我需要解决的问题。

这是相关的控制器代码:

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);
        }

Index.cshtml:

@using GUI.Models
@model IEnumerable<GUI.Models.CategoryViewModel>
@{
    ViewBag.Title = "Index";
}
<h2>Categories</h2>
<p>
    @Html.ActionLink((HttpUtility.HtmlDecode(" &laquo;") + " Back to Admin Page"), "Index", "Admin", null, new { @class = "btn btn-primary btn-large" }) | 
    @Html.ActionLink("Create New Category" + (HttpUtility.HtmlDecode(" &raquo;")), "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');
                }
            });
        }

请注意,此 javascript 函数对控制器进行 ajax 调用:

function searchCategories() {
            var searchWord = $('#searchString').val();

            $.ajax({
                url: '/Category/SearchCategories?searchString=' + searchWord,
                type: 'GET',
                sucess: function (data) {
                    alert('Koppling');
                }
            });
        }

我想用来返回搜索结果的部分视图:

@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")


}

我还注意到,ajax 请求的状态码为“200 OK”。 那我该如何解决呢?

【问题讨论】:

    标签: ajax asp.net-mvc partial-views


    【解决方案1】:

    尝试在控制器中重命名:

    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>Search:</h3>
        @Html.TextBox("searchString", null, new { id = "Search" })
        <input type="submit" value="Search" class="btn btn-primary" />
    }
    <div id="searchResults"></div>
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 2016-01-12
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      相关资源
      最近更新 更多