Pass javascript array to C# via json

心不动则不痛 提交于 2019-12-07 18:52:31

问题


I´m using this javascript array:

 var exportOptions = [{
            jobName: ""},
            {exportType: ""},
            {attachToEmail: ""},
            {distributorName: ""},
            {vistaNumber: ""},
            {customerName: ""},
            {competitors: ""},
            {agreementType: ""},
            { annualPotential: "" },
            {businessCase: ""
        }];

And I passing to ASP.NET codebehind(C#) with this code:

                    $.ajax({
                        type: 'POST',
                        url: 'Epad.aspx/generateReport',
                        data: "{'columnList': '" + columnList + "', 'exportOptions':" + JSON.stringify( exportOptions ) + "}",
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        async: true,
                        cache: false,
                        });

And reading in C# with this method:

public static void generateReport(string columnList, Object exportOptions) {}

columnList is a string variable this values I can retrieved from C# but the exportOptions's values I cannot see in the debugger... I can see the names of the exportOptions array key in Object exportOptions(C# Object) but never pass the values...

Can anybody help me with this?


回答1:


Solved similar issue by this way:

JS code (part of processing function):

    var ords = [];
    $(".order-count-input").filter(function() {
        return $(this).val() > 0;
    }).each(function() {
        ords.push({                
            GoodsId: $(this).attr("goodsId"),
            Amount: $(this).val()
        });
    });

    var data = {
        orders: ords,
        orderId: id
    };

    var params = {            
        url: actionUrl,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: function (data) {
            window.location.replace(data.redirect);
        }
    };

    $.ajax(params);

Controller action:

[HttpPost]
public JsonResult PostOrder(long orderId, PostOrderViewModel[] orders)

Model:

[Serializable]
public class PostOrderViewModel
{
    public long GoodsId { get; set; }

    public int Amount { get; set; }
}



回答2:


I would first check that the values are sent from the client side. I would use the browser debugger. There you can set breakpoints and see if the variable you send (JSON.stringify(exportOptions)) has values.

You could use the F12 button (either from the Chrome, or Firefox) and use the javascript debugger. In chrome you can do it in "Script" tab. In Firefox you can do it in "Sources" tab.

Hope I helped!



来源:https://stackoverflow.com/questions/20778628/pass-javascript-array-to-c-sharp-via-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!