简体   繁体   中英

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.

[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:

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:

$.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.

Use JSON.stringify to convert your javascript object to it's json string version and specify the contentType as " 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM