Thenis Thenis - 3 months ago 29
Ajax Question

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:
enter image description here
And this is what I get when I search
enter image description here

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

Answer

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.