0

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
  • Are you using some additional library or framework? Because in general, the string @item.BookId will 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 then returnBook(document.getElementById("bookId").value) (or $('#bookId') if you use jQuery as your tags imply). Commented Oct 26, 2015 at 8:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.