Sending JSON object successfully to ASP.NET WebMethod, using jQuery

后端 未结 6 1441
执念已碎
执念已碎 2020-12-05 00:55

I\'ve been working on this for 3 hours and have given up. I am simply trying to send data to an ASP.NET WebMethod, using jQuery. The data is basically a bunch of key/value p

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 01:29

    The following is a code snippet from our project - I had trouble with not wrapping the object as a string and also with Date values - hopefully this helps someone:

            // our JSON data has to be a STRING - need to send a JSON string to ASP.NET AJAX. 
            // if we specify an actual JSON object as jQuery's data parameter, it will serialize it as ?k=v&k=v pairs instead
            // we must also wrap the object we are sending with the name of the parameter on the server side – in this case, "invoiceLine"
            var jsonString = "{\"invoiceLine\":" + JSON.stringify(selectedInvoiceLine) + "}";
    
            // reformat the Date values so they are deserialized properly by ASP.NET JSON Deserializer            
            jsonString = jsonString.replace(/\/Date\((-?[0-9]+)\)\//g, "\\/Date($1)\\/");
    
            $.ajax({
                type: "POST",
                url: "InvoiceDetails.aspx/SaveInvoiceLineItem",
                data: jsonString,
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
    

    The server method signature looks like this:

        [WebMethod]
        public static void SaveInvoiceLineItem(InvoiceLineBO invoiceLine)
        {
    

提交回复
热议问题