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?
@item.BookIdwill not magically get replaced by the value of some field. In general, you would have to get it from your form, for example<input type='hidden' id='bookId' value='...' />and thenreturnBook(document.getElementById("bookId").value)(or$('#bookId')if you use jQuery as your tags imply).