简体   繁体   中英

Using ajax to pass pass values to controller from view in MVC

I have the following in my Razor view file:


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

<script>
function getFavouriteBooks() {
    var ids = JSON.parse(localStorage.getItem("bookIds"));
    $.ajax({
        type: "POST",
        url: '@Url.Action("Favourites", "Home")',
        data: ids,
        dataType: "javascript"
    });
}
</script>

And in my Home Controller, this action:

public async Task<ViewResult> Favourites(string[] ids)
        {
            // var bookList = code that retrieves list of all books

            var favouriteBooks = bookList.Any(book => ids.Contains(book.Id));

            return View("Index", favouriteBooks);

        }

When user clicks 'Display Favourites' I get a 500 error for localhost/Home/Favourites. Can anyone help me see where I've gone wrong here?

Update: bookIds is an array of string Ids.

So I think there is a couple of things going on here.

I am assuming it's a “get” request not a “post” request. Since you want to display the books. If you want to “get” all that match an id the easiest way would be to get the total response and loop through it. If it is just for a small project if it's serious you want to want to change your SQL to find where ID.

But assuming you just want assistance with the JavaScript.

First of all if you put your javascript in line like that you need to also handle the response in line which isn't going to be syntactically very friendly. After all we are not writing php.

The second point about async functions is that you need a response which will happen asynchronously so need to await. Also need to handle the promise

I have simplified what I think is the solution here to use fetch instead of ajax to avoid all the jquery and Ajax setup with code pen but the logic should be there for you to follow up.

https://codepen.io/sijbc/pen/qBRrgBG?editors=1111

  fetch('https://api.github.com/users')
     .then(res => res.json())//response type
     .then(data => console.log(data))

Also found this article which would be worth checking out

https://medium.com/front-end-weekly/ajax-async-callback-promise-e98f8074ebd7

Update data with added contentType in ajax call as below and check again

function getFavouriteBooks() {
    var ids = JSON.parse(localStorage.getItem("bookIds"));
    $.ajax({
        type: "POST",
        url: '@Url.Action("Favourites", "Home")',
        // jQuery refers below mentioned contentType to serialize data in JSON format
        // Without this, serialization will be url encoded string
        contentType: "application/json; charset=utf-8",
        // Assuming ids as a array of strings
        // data to be an object that holds Action methods parameters as it's properties
        // Stringify object before assigning to data
        data: JSON.stringify({
            ids: ids
        }),
        dataType: "javascript"
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM