Ensuring Smooth Transfer: Sending Local Storage Data to MVC Controller

I'm attempting to send an array of strings from my local storage (key value) to an MVC controller. Here's the code I have so far:

Inside the cshtml View file:

 <script>

        function getFavouriteBooks() {
            var ids = JSON.parse(localStorage.getItem("bookIds"));
            
            $.ajax({
                type: "POST",
                traditional: true,
                url: '@Url.Action("Favourites", "Home")',
                data: { ids: ids },
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    alert(result.Result);
                }
            }});
        }
    </script>


   <button onClick="getFavouriteBooks()">Display Favourites</button>

The Controller section in my code:

public async Task < ViewResult > Favourites(string ids) {
    
    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");
}

     

Although the controller action is being successfully called on button click, the 'ids' parameter continues to be null despite containing values in the console. Can anyone point me in the right direction?

Answer №1

Based on the description you provided, it seems like the issue is related to expecting an asynchronous function to behave synchronously,

await 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());
        }

Consider adding await before calling the foreach loop or using a for-in loop instead.

Answer №2

Appreciate the support from all of you, it turned out that the fix was to modify this segment of the ajax request to:

data: { ids: localStorage.getItem('videoIds') },

Answer №3

Testing was conducted in Visual Studio for this code.

To begin, you will need to establish a viewModel:

public class IdsViewModel
    {
         public string[] Ids { get; set; }
    }

Next, update the following:

var ids = JSON.parse(localStorage.getItem("bookIds"));
            // returns: ["1", "2", "3"]
// Alternatively, you can also use 
var ids = localStorage.getItem('videoIds');  //it will still function properly


            $.ajax({
                type: "POST",
                traditional: true,
                url: '@Url.Action("Favourites", "Home")',
                data: { ids: ids },
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (result) {

Replace it with the following:

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

  $.ajax({
  type: "POST",
   url: '/Home/Favourites',
   data: { ids:ids },
 success: function (result) {
....

Lastly, update the action as shown below:

public async Task <ActionResult> Favourites(IdsViewModel viewModel) {

var ids=viewModel.Ids;

.....

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

Even with React.memo(), functional components continue to trigger re-renders

I am facing an issue with my button component that contains a button inside it. The button has a state isActive and a click function passed to it. Upon clicking the button, the isActive flag changes, triggering the app to fetch data accordingly. However, t ...

Google Maps Circle Radius Functionality Malfunctioning

I've been trying to implement a map scaling feature using a slider in my code but I'm having trouble getting it to work. While the map is displaying correctly, the radius won't update as intended. Any assistance with this would be greatly ap ...

Interact with a modal element using puppeteer

I'm having trouble clicking on the email login button inside a modal using Puppeteer for automation. The code is not able to find the modal element. Can someone assist me in debugging this issue? const puppeteer = require('puppeteer'); ( ...

Expand the accordion to reveal all the content

I'm facing an issue with my accordion where a scrollbar appears in every content section. To fix this, I tried setting overflow: hidden in the CSS: .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: hidd ...

"An issue with preventing default behavior when clicking on a jQuery element

I need some assistance preventing a JQuery onclick function from scrolling the page to the top. I have tried using preventDefault() without success. You can find the code on this website: Below is the code snippet that I am currently using: $( document ...

Utilizing jQuery for AJAX requests on a timed loop

I'm puzzled by a situation involving an AJAX call within an interval. It seems that the code doesn't work as expected, and I'm wondering why. Initially, I had this code snippet which wasn't functioning properly: setInterval($.ajax({ ...

Learn the method of showcasing a JavaScript variable value within an HTML href tag

Currently, I am in the process of rewriting my URL and category name to be passed into the URL. For this purpose, I am creating a URL friendly string using the following JavaScript function: function getUrlFriendlyString(str) { // convert spaces to &ap ...

Creative Blueprint

Our company currently operates 3 browser based games with a team of just 4-5 coders. We are looking to enhance the collaboration within our coding team and streamline our processes. Considering the fact that our games are built using a mix of html, php, j ...

Attempting to alter an image with a click and then revert it back to its original state

I'm currently working on a feature that toggles an image when a specific class is clicked. The code I have so far successfully switches from 'plus.png' to 'minus.png' upon clicking, but I need it to switch back to 'plus.png&ap ...

The button text in Bootstrap 5 is black instead of white as shown in their demo

During the installation of Bootstrap 5, I encountered an issue where many of my buttons are displaying a black font instead of the expected white font as shown in the Bootstrap 5 Documentation For instance, the .btn-primary button on the official Bootstra ...

.NET Clean architecture - organizing code into separate projects

When working on my projects, I always aim for clean architecture by using Entity Framework. It's been smooth sailing so far with my project structure including Domain, Application, and Infrastructure layers. Recently, I decided to add a Blazor server- ...

Determine whether the click occurs inside or outside of a bar on a ChartJS graph

I'm currently working with a bar graph using chartJS. I'm trying to figure out how to detect where the user clicked - whether it was inside or outside of the bar region in chartJS. const waterFChart = new Chart(canvasRef.current, { plugins: [ ...

Creating HTML input elements dynamically using Javascript

<body> <form action="insertquestion.php" method="POST"> <script> function generateInputs(){ var prefix = "answer"; var number = 1; for(var i = 0; i < 5; i++){ ...

Exploring the data-* attribute in jQuery

Currently, I have a form structured as follows: <div data-role="page" data-last-value="43" data-hidden="true" data-bind='attr : {"name":"John"}'></div> My objective is to modify the name attribute from "John" to "Johnny". I am att ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

Troubleshooting Problems with Data Display in Rails 3 and JQuery

Running a Rails3 application integrated with JQuery. I am encountering an issue with the below code snippet (Note: there is a div with id 'new' as well) $.ajax({ type: "GET", url: '/users/new', success: function(data) { ...

Update search results when performing a new search on a web application (without using jQuery)

My simple web app interacts with an API to retrieve search results from a database and utilizes ajax to insert them into an empty ul element on the page (employing JSONP for cross-domain requests). I am struggling to achieve this functionality using plain ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

Exploring the world of lighting and shadows in WebGL and Three.js

I'm having difficulty focusing lights on specific targets, specifically the main character, while also darkening the background. Additionally, I'm experiencing issues with the shadows not working properly in my code snippet related to lights and ...

Preserve selected option in select box after page refresh in JSP

I'm working on a jsp page that contains a simple select html element. Right now, when I select an option and click the Wyswietl button, the page refreshes, the table data is refreshed, but the selected option resets to default... How can I make it sta ...