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

送分小仙女□ 提交于 2021-01-21 11:54:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!