Search code examples
javascriptc#ajaxasp.net-mvcrazor

How to pass local storage item to MVC controller


I am trying to pass an array of strings from my local storage (key value) to MVC controller. Here's my code:

In cshtml View file:

 <script>

        function getFavouriteBooks() {
            var ids = JSON.parse(localStorage.getItem("bookIds"));
            // returns: ["1", "2", "3"]

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

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");
}

     

The controller action gets called successfully on the button click but the ids parameter is always null even though it isn't when in the console. Where am I going wrong?


Solution

  • Thanks for your help everyone, the solution was actually to change this part of the ajax call to:

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