简体   繁体   English

ASP.NET MVC 5-部分视图不适用于我的AJAX实时搜索

[英]ASP.NET MVC 5 - Partial view doesn't work with my AJAX live search

I have the following problem 我有以下问题

In my ASP.NET MVC 5 app I want to list all users and have a live search bar that updates as you type. 在我的ASP.NET MVC 5应用程序中,我想列出所有用户并拥有一个实时搜索栏,该栏会在您键入时更新。 I made it and it works, but it doesn't return a partial view, instead it returns a whole new page like so. 我做到了,它可以工作,但是它不返回部分视图,而是像这样返回一个全新的页面。

This is the page that lists all the users: 这是列出所有用户的页面: 在此处输入图片说明 And this is what I get when I search 这就是我搜索时得到的 在此处输入图片说明

This is my controller(AdminController.cs) 这是我的控制器(AdminController.cs)

   public class AdminController : Controller
{
    protected readonly ApplicationDbContext db = new ApplicationDbContext();

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Users()
    {
        var users = db.Users.ToList();

        return View(users);
    }

    public ActionResult Search(string query)
    {
        var result = db.Users.Where(u => u.UserName.ToLower().Contains(query.ToLower())).ToList();

        return PartialView("_UsersResult", result);
    }
}}

My View(Users.cshtml) 我的看法(Users.cshtml)

@model List<Forum.Models.ApplicationUser>



@using (Ajax.BeginForm("Search", null,
    new AjaxOptions
    {
        HttpMethod = "GET",
        UpdateTargetId = "results",
        InsertionMode = InsertionMode.Replace
    }, new {id = "searchForm"}))
{
    <input name="query" placeholder="Search" oninput="$('#searchForm').submit()"/>
    <input type="submit" value="Search"/>
}


<div id="results">
@Html.Partial("_UsersResult", Model)
</div>

And my Partial View(_UsersResult.cshtml) 还有我的局部视图(_UsersResult.cshtml)

@model List<Forum.Models.ApplicationUser>

@foreach (var user in Model)
{
    <h3>@user.UserName</h3>
}

If you want to render a partial view by making a request to server, then using ActionResult is not the correct way. 如果要通过向服务器发出请求来呈现局部视图,则使用ActionResult不是正确的方法。 You will have to return PartialViewResult from the controller. 您将必须从控制器返回PartialViewResult。

public PartialViewResult Search(string query)
    {
        var result = db.Users.Where(u => u.UserName.ToLower().Contains(query.ToLower())).ToList();

        return PartialView("_UsersResult", result);
    }

Hope that solves the issue. 希望能解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM