How to refresh only part of the Index page in MVC 5?

You will, in fact, need to use AJAX.

The best approach, as I see, is to have a partial view and issue a AJAX Load (jQuery.load in jQuery) to it.


I would put a form in your search partial. Then have some action post that, via JQuery, to your GetResults Action, which should return:

return PartialView("~/Views/Shared/Results.cshtml", results); 

Then, in the success callback of your JQuery post, spit the returned results to your $("#div_Results") like so:

$.ajax({
    url: '/Home/GetResults',
    type: "POST",
    dataType: "html",
    data: $("#FormId").serialize(),
    success: function (data) {
        //Fill div with results
        $("#div_Results").html(data);
    },
    error: function () { alert('error'); }
});

Unless I have a typo or something, that should work. You'll need to replace the form selector with the Id of your form tag.


though this question has an answer already, I thought I would post an alternative approach which would also work. This approach uses the same action method and only checks if the Request is an Ajax call which then only replaces part of the body. Here is the relevant code only.

//The search form

@using (Ajax.BeginForm("Index", "Home", 
    new AjaxOptions()
    { 
        HttpMethod = "GET", UpdateTargetId = "my-posts", 
        InsertionMode = InsertionMode.Replace 
    }))
{
    <input type="text" name="term" placeholder="Search B.I & G" />
    <input type="submit" value="" />
}

//Portion of the View

<section>
<div id="my-posts">
    @Html.Partial("_Posts", Model.Posts)
</div>

Now here is the Index action method, if the Request is an AjaxRequest, it returns a Partial View which replaces contents of div with id my-posts. If the Request isn't an Ajax request then it loads the whole View.

public async Task<ActionResult> Index(string term)
{
     var viewModel = new HomeFeedsViewModel();
     viewModel.Posts = await Task.Run(() =>
                   db.Posts.Include("Comments")
                   .Include("By").OrderByDescending(o => o.PostedOn)
                   .ToList());
    //Return a Partial View which replaces content on the View
    //only if the Request is an Ajax Request
    if (Request.IsAjaxRequest())
    {
        viewModel.Posts = viewModel.Posts
            .Where(a => a.Title.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0
                     || a.Message.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0
            );
        return PartialView("_Posts", viewModel.Posts);
    }

    return View(viewModel);
}

Hope this helps someone.