使用 Ajax 在 C# 中将 int 从视图传输到控制器 [英] Transferring an int from view to controller in C# using Ajax
本文介绍了使用 Ajax 在 C# 中将 int 从视图传输到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个整数从我的视图传输到我的控制器.我正在使用 Ajax 来执行此操作,以下是我的 html 代码:
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);"/>
我的ajax:
function returnBook(id) {
console.log(id);
var bookID = id;
var url= '/AuthenticatedUser/ReturnBook';
$.ajax({
url: url,
type: 'POST',
data: bookID,
success: function (results) {
}
});
}
我的控制器:
[HttpPost]
public ActionResult ReturnBook(string id)
{
return View();
}
在我的控制器中,当我使用字符串时,会调用该方法,但 id 仍设置为 null.但是,如果我使用int id",则根本不会调用该方法,并且会收到 500 错误.知道如何将 id 从视图传递给控制器吗?
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?
推荐答案
改为发送对象:
data: { id:bookID },
现在您可以在控制器上使用此对象的键 id
来获取它的值.
Now you can use the key id
of this object at your controller to get the value of it.
这篇关于使用 Ajax 在 C# 中将 int 从视图传输到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文