[英]MVC: Send object and integer to controller as JSON
I'm trying to send a custom object and an integer to my controller action using jQuery AJAX. 我正在尝试使用jQuery AJAX向我的控制器操作发送自定义对象和一个整数。
[HttpPost]
public JsonResult GetFilenameSuggestion(Document document, int tradeId)
{
//do stuff...
}
In my JS, I've tried to create the json sent to the controller in several ways, including: 在我的JS中,我尝试以多种方式创建发送到控制器的json,包括:
var json = JSON.stringify({ document: document, tradeId: tradeId });
//or
var json = { document: JSON.stringify(document), tradeId: tradeId };
//or
var json = { document: document, tradeId: tradeId };
and here's my jQuery AJAX: 这是我的jQuery AJAX:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Document/GetFilenameSuggestion",
data: json,
error: function (XMLHttpRequest, textStatus, errorThrown) {
//do bad stuff...
},
success: function (data) {
//do good stuff...
});
Any suggestions on how to do this? 有关如何执行此操作的任何建议? I am getting an internal server error when the ajax posts, and I'm 99% sure it's due to how the arguments are being passed to the controller action. 我在ajax发布时收到内部服务器错误,我有99%的把握是由于参数如何传递到控制器操作。
Use JSON.stringify
to convert your javascript object to it's json string version and specify the contentType
as " application/json
". 使用JSON.stringify
将您的JavaScript对象转换为json字符串版本,并将contentType
指定为“ application/json
”。
The below code should work fine. 下面的代码应该可以正常工作。
var model = { document: { DocumentName: "Dummy" }, tradeId: 34 };
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Document/GetFilenameSuggestion",
data: JSON.stringify(model),
error: function(XMLHttpRequest, textStatus, errorThrown) {
//do bad stuff...
},
success: function(data) {
//do good stuff...
}
});
for this action method signature 为此操作方法签名
[HttpPost]
public JsonResult GetFilenameSuggestion(Document document, int tradeId)
{
// to do : return some useful JSON data
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.