MVC:将对象和整数作为JSON发送到控制器

MVC: Send object and integer to controller as JSON

本文关键字:JSON 控制器 对象 整数 MVC      更新时间:2023-09-26

我正在尝试使用jQueryAJAX向我的控制器操作发送一个自定义对象和一个整数。

[HttpPost]
public JsonResult GetFilenameSuggestion(Document document, int tradeId)
{
    //do stuff...
}

在我的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 };

这是我的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...
});

有什么建议吗?当ajax发布时,我收到了一个内部服务器错误,我99%确信这是由于参数是如何传递给控制器操作的。

使用JSON.stringify将javascript对象转换为json字符串版本,并将contentType指定为"application/json"。

下面的代码应该可以正常工作。

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...
    }
});

对于此操作方法签名

[HttpPost]
public JsonResult GetFilenameSuggestion(Document document, int tradeId)
{
    // to do : return some useful JSON data
}
相关文章: