简体   繁体   中英

How to send JSON Array to an ASP.NET MVC Controller

I am trying to send JSON array to ASP MVC Controller. I first tried a JSON object and it did work but failed while I tried the array JSON object. As the coding showed below, I expected to get the ListForm2 to be,

ListForm2[0].MarketID = 1, ......

ListForm2[1].MarketID = 2, ......

However, I got the ListForm2=null. What's wrong in my coding?

function ProcessSaveView(area, bChecked, bChart, saveName) {
    var jsondata = [{ MarketID: 1, ForecastPointTypeID: 5, ForecastPointID: 21, CustomTimeZoneID: "ET-Prevailing", IsChart: true },
                    { MarketID: 2, ForecastPointTypeID: 5, ForecastPointID: 51, CustomTimeZoneID: "ET-Prevailing", IsChart: true }];

    $.ajax({
        type: "POST",
        url: "./charts/SaveViewToDatabase",
        dataType: "json",
        traditional: true,
        data: jsondata,
        success: function (result) {
            if (result.success) {
                alert("Save View successful!");
            } else {
                alert("Duplicate View already exist. Not save!");
            }
        },
        error: function () {
            alert("No market, load type & region is selected!");
        }
    });
}

[HttpPost]
public ActionResult SaveViewToDatabase(testJsonObject[] ListForm2)
{
    return Json(new { success = true });
}

public class testJsonObject
{
    public int ForecastPointID { get; set; }
    public int MarketID { get; set; }
    public int ForecastPointTypeID { get; set; }
    public string CustomTimeZoneID { get; set; }
    public bool IsChart { get; set; }
}

Try the following:

$.ajax({
    type: "POST",
    url: "./charts/SaveViewToDatabase",
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify(jsondata),
    success: function (result) {
        if (result.success) {
            alert("Save View successful!");
        } else {
            alert("Duplicate View already exist. Not save!");
        }
    },
    error: function () {
        alert("No market, load type & region is selected!");
    }
});

See added contentType and JSON.stringify into data attribute.

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