简体   繁体   中英

Transferring an int from view to controller in C# using Ajax

I want to transfer an integer from my view to my controller. I am using Ajax to do this and below is my html code:

<input type="button" class="btn btn-default" value="Yes" id="return"
onclick="returnBook(@item.BookID);"/>

My ajax:

function returnBook(id) {
console.log(id);
var bookID = id;
var url= '/AuthenticatedUser/ReturnBook';
$.ajax({
    url: url,
    type: 'POST',
    data: bookID,
    success: function (results) {
    }
});

}

My controller:

[HttpPost]
    public ActionResult ReturnBook(string id)
    {
        return View();
    }

In my controller, when I use a string, the method is invoked but the id remains set to null. However, if I use a 'int id', the method is not invoked at all and I get a 500 error. Any idea how I can pass the id from view to controller?

MVC will automatically try to match data values passed from your web page to the arguments declared in your controller.

So when you are sending a variable bookID MVC will try to match that to a variable named bookID in your controller's argument list. As that argument doesn't exist the associated value is disregarded.

To fix your problem you either want to change your controller declaration to -

public ActionResult ReturnBook(string bookId)

or change your data declaration to either

data: id,

or (as Jai suggests) -

data: { id:bookID },

send an object instead:

data: { id:bookID },

Now you can use the key id of this object at your controller to get the value of it.

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