Search code examples
javascriptajaxasp.net-mvcrazor

MVC refreshing page after Ajax call to controller


I have the following in my controller:

public async Task < ViewResult > Favourites(string ids) {
    // code that fetches book data from API 

    if (data != null)

    {
        var bookList = JsonConvert.DeserializeObject < Book[] > (data);

        foreach(var book in bookList) {
            var matches = new List < bookList > ();
            if (bookList.All(book => ids.Contains(book.Id))) {
                matches.Add(book);
            }

            return View("Index", matches.ToArray());
        }
    }
    return View("Index");
}

And this in my view:

   <script>

        function getFavouriteBooks() {
            var ids = JSON.parse(localStorage.getItem("bookIds"));

            $.ajax({
                type: "POST",
                url: '/Home/Favourites',
                data: { ids: localStorage.getItem('bookIds') },
                success: function (response) {
                    window.location.href = '/Home/Favourites/' + ids ;
                }
            });
        }
    </script>

I don't think window.location.href = '/Home/Favourites/' + ids; is correct but my goal is to reload the page with the View called from my controller (return View("Index", matches.ToArray());) and am not sure how to do this.

The first time the controller is hit the parameter is correctly populated with the data, but the second time it's empty. I know this is because it's empty.

Please can someone explain how to get the View to load after the ajax call with the ids parameter?


Solution

  • The solution was to change the ajax call success part to:

          success: function (data) {
                            $("body").html(data);
                        }