Refreshing a page in MVC after making an Ajax call to the controller

In my controller, I have the following code:

public async Task < ViewResult > Favourites(string ids) {
    // API call to fetch book data 

    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 in my view, this is the script used:

   <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 am unsure about using

window.location.href = '/Home/Favourites/' + ids;
and would like the View called from my controller (
return View("Index", matches.ToArray());
) to reload. Any suggestions on how to achieve this?

The parameter is correctly populated with data the first time the controller is accessed, however, it is empty the second time due to the absence of data.

If anyone can provide insights on how to load the View after the ajax call with the ids parameter, I would greatly appreciate it.

Answer №1

To ensure your controller is only accessed via a GET request, you may need to update the ajax settings or include the HttpPost attribute in your controller code.

type: "GET",

Answer №2

The resolution involved modifying the success portion of the ajax call to:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capturing click events on a stacked area chart with nvd3

Could someone assist me in capturing the click event on a nvd3 stacked area chart? I have successfully managed to capture tooltip show and hide events but am struggling with the click event. How can I obtain information about the clicked point? Please help ...

The head.js feature similar to "Modernizr" does not recognize ms-edge

It has come to my attention that the head.js script is unable to detect the Microsoft "Edge" browser correctly. In addition, it erroneously adds classes like chrome and chrome55 to the <html> element. Is there a better way to handle this issue? The ...

javascript: revealing the identity of a click event handler

Here I am looking to create a click function with a specific name and parameters for the purpose of code reusability. This will allow me to write one generic function that can be used for common tasks like enabling users to delete various types of data. I ...

Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreci ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

What is the best way to turn off the annoying pop-up messages that show up for input validation, specifically the one that says "Please complete

Currently using Angular 2, my form has input fields similar to this simplified version: <input class="body-text1" type="text" [(ngModel)]="model.name" name="name" required minlength="1"> <!--more inputs like this --> Although I have implement ...

Tips for updating data within an array using a copied object

Just starting out with JavaScript Could you assist me with a basic inquiry, please? For instance, I have an array like this: const array = [{ id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', countr ...

Why am I encountering this export issue while attempting to integrate a NextAuth.js Provider with Next.js?

Embarking on my first project in React/Next.js, I opted to employ NextAuth.js for authentication. Following the initial steps outlined in the Getting Started guide provided by NextAuth, I have successfully set up a [...nextauth].js page featuring the code ...

What is the best way to execute this query using CodeIgniter?

This is the controller method public function ajaxLoad() { $data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC"); $data['content'] = $this->load->view('item', $data, true); $data = ...

Steer clear of constantly reloading the layout page in ASP.NET Core MVC

Every time I select a nav link in my Core MVC application, the entire layout is refreshed, causing the active nav link to reset. Is there a way to only reload the @RenderBody() section without refreshing the entire page? I have reviewed this answer but it ...

Clicking on a button will allow me to select only a portion of text within a specific cell of

Inside a table, there is a paragraph of text enclosed in a <td></td> element. Take for example the following passage. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

Response from successful AJAX call to retrieve data

Here's the code snippet I'm currently working with: var array = []; $('#next1').on('click', function(){ var dataString='company= '+$(this).closest('.inside').find('select').val(); $.ajax( ...

Incorporate a sleek Vueitfy user interface seamlessly into your current website

Recently, I put together a sleek user interface for a web application with the help of Nuxt.js and Vuetify.js (which utilizes Vue.js code). Although my design is top-notch, I now face the challenge of integrating it into an existing website that does not ...

Using an if statement to run a script in Npm

Is there a way to configure an npm run script to use different AWS accounts based on the environment? { "config": { "acc": if ({npm_config_env} == "dev") "account1" else "account_2" }, "scr ...

Develop a personalized API using Strapi that involves integrating data from two distinct tables

I am relatively new to Strapi, so please forgive my lack of experience. My goal is to set up a custom route for retrieving complex data using two related tables. I have relationships with the "items" and "comments" tables. My approach involves selecting ...

How can I organize data from A to Z in alphabetical order in React Native when the user chooses the A to Z option from the dropdown menu?

I am working on a screen that can display up to 1000 data retrieved from the API. Here is the image: https://i.sstatic.net/ErbDD.png Now, I have implemented a drop-down box where users can select alphabetically from A to Z. After selecting an alphabetic ...

Discover the "route" of a JSON element using JavaScript

I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model for dynamically generated forms. Below is my current code: my_code.js: var my_data = { name: "fred", numbe ...

Avoiding layout shift when a button is clicked in React JS

I am working on a Drawer example and following the instructions provided at https://mui.com/material-ui/react-drawer/ Everything is functioning as expected, but I am encountering an issue where my content shifts to the right when the drawer opens, and ret ...

Pass the ASP.NET MVC model onto the AngularJS scope

Here is the code snippet from my view with temporary JavaScript code for testing: I am trying to assign the ASP.NET MVC model (@Model) to the AngularJS scope ($scope.person). Any suggestions on how to accomplish this? Thank you, The View @model MyApp. ...

Is it possible to dynamically change the port for an Express server?

Here is a common question that often arises among beginners, as I had the same query when I first started Is there a way to set the port for express without manually coding it or selecting a port yourself? This was something that puzzled me during my init ...