问题
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?
回答1:
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.
回答2:
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 },
来源:https://stackoverflow.com/questions/33341668/transferring-an-int-from-view-to-controller-in-c-sharp-using-ajax