简体   繁体   中英

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. 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)

   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)

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

@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. You will have to return PartialViewResult from the controller.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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