How to pass complex key-value parameters form view to controller in mvc?

Viewed 597

I have a problem with ajax while sending complex key-value pairs from view to controller. I wrote my ajax queries. Except "currentStateDatas" all other variables are passing correctly to controller. But, currentStateDatas comes null from view. Controller waits "string" for "currentStateDatas" because I need string type for it. I have could not figure out the problem. Could you please help me ? By the way "currentStateDatas" contains json. It has too many nested key value pairs.

currentStateDatas = {};
//some values are taken from forms.
$.ajax({
        url: "@Url.Action("SaveTempReport", "Report")",
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "categoryIds": categoryIds, "reportName": reportName, "Description": description, "tempReportId": tempReportId, "chartState": currentStateDatas, "deparmentIds": deparmentIds}),
        success: function (response) {

        }
    });
1 Answers

Your controller waits for currentStateDatas as a string, but in your js code it's an object, you should also convert currentStateDatas to string by using JSON.stringify.

$.ajax({
        url: "@Url.Action("SaveTempReport", "Report")",
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "categoryIds": categoryIds, 
                               "reportName": reportName, 
                               "Description": description, 
                               "tempReportId": tempReportId, 
                               "chartState": JSON.stringify(currentStateDatas), 
                               "deparmentIds": deparmentIds}),
        success: function (response) {
        }
    });
Related