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

前端 未结 3 1862
执念已碎
执念已碎 2020-12-16 17:18

The Index page contains two partial views. One is for the user to enter the search criteria, the other to show the results. How to update the data in the Results view only ?

3条回答
  •  庸人自扰
    2020-12-16 17:53

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

    //Portion of the View

    @Html.Partial("_Posts", Model.Posts)

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

提交回复
热议问题