Search code examples
jqueryajaxasp.net-mvcreloading

jquery ajax call reload page


I am working on an asp.net mvc page where I am passing a string to controller post method to get records and populate on view. But With my code My viewmodel gets correct records with ajax call but view is having same old number of records. I think we have to refresh it again after jquery ajax call. Could you please throw some idea on this. Below is what I tried. Please feel free to suggest code changes if it is not with standards.

$.ajax({
    type: "POST",
    url: "/Default/MyProjects",
    data: { 'QuerySeperated':  querySeperated  },
    success: function (result) {
        //location.reload();
    },
    error: function (result) {

    }
});



[HttpGet]
public virtual ActionResult MyProjects(int? id, string QuerySeperated)
{
    var dataAccessHelper = new DataAccessHelper(true);
    IList<test> myProjects;
    if (QuerySeperated == null)
    {
        myProjects = dataAccessHelper.GetMyProjects(id);
    }
    else
    {
        myProjects = dataAccessHelper.GetMyProjects(id).Take(2).ToList();
    }
    var myProjectsViewModel = new MyProjectsViewModel() { GetMyProjects = myProjects };
    return View(myProjectsViewModel);
}

[HttpPost]
public virtual ActionResult MyProjects(int? id, string QuerySeperated, string m)
{
    var dataAccessHelper = new DataAccessHelper(true);
    IList<test> myProjects = dataAccessHelper.GetMyProjects(id).Where(p => p.Title == "New Project").ToList();
    var myProjectsViewModel = new MyProjectsViewModel() { GetMyProjects = myProjects };

    return RedirectToAction("MyProjects", new { QuerySeperated });
}

Solution

  • You're right that you have to refresh the page for update to webgrid. One way of doing this is to use ajax just to redirect instead of actually doing the work itself. Change your action method to something like this:

    [HttpPost]
    public ActionResult MyProjects(int? id, string QuerySeperated, string m)
    {
        var redirectUrl = new UrlHelper(Request.RequestContext).Action("MyProjects", "ControllerName", new { QuerySeperated });
        return Json(new { Url = redirectUrl });
    }
    

    this will just return the url of the get method. You'll need to change this so it also takes the parameters into account. Then change your ajax call to:

    $.ajax({ type: "POST",
             url: "/Default/MyProjects",
             data: { 'QuerySeperated':  querySeperated  },
               success: function (response) {
                   window.location.href = response.Url;
               },
               error: function () {
               }
      });