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

后端 未结 6 1413
执念已碎
执念已碎 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:17

    When using AJAX.NET I always make the input parameter just a plain old object and then use the javascript deserializer to covert it to whatever type I want. At least that way you can debug and see what type of object the web method in is recieving.

    You need to convert your object to a string when using jQuery

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
                <Scripts>
                    <asp:ScriptReference Path="~/js/jquery.js" />
                </Scripts>
            </asp:ScriptManager>
            <div></div>
        </form>
    </body>
    </html>
    <script type="text/javascript" language="javascript">
        var items = [{ compId: "1", formId: "531" },
            { compId: "2", formId: "77" },
            { compId: "3", formId: "99" },
            { status: "2", statusId: "8" },
            { name: "Value", value: "myValue"}];
    
            //Using Ajax.Net Method
            PageMethods.SubmitItems(items,
                function(response) { var results = response.d; },
                function(msg) { alert(msg.d) },
                null);
    
            //using jQuery ajax Method
            var options = { error: function(msg) { alert(msg.d); },
                            type: "POST", url: "WebForm1.aspx/SubmitItems",
                            data: {"items":items.toString()}, // array to string fixes it *
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            async: false, 
                            success: function(response) { var results = response.d; } }; 
            jQuery.ajax(options);
    </script>
    

    And the Code Behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Script.Serialization;
    using System.Web.Script.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace CustomEquip
    {
        [ScriptService]
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
            [WebMethod]
            public static void SubmitItems(object items)
            {
                //break point here
                List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 01:20

    This is the way you define your data (JSON)

    data: { 'items': items },
    

    and the this the way it should be

    data: '{ items: " '+items +' "}',
    

    basically you are serializing the parameter.

    0 讨论(0)
  • 2020-12-05 01:26

    Decorate your [WebMethod] with another attribute:

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    

    I believe this is in System.Web.Services.Scripting...

    0 讨论(0)
  • 2020-12-05 01:29

    In your example, it should work if your data parameter is:

    data: "{'items':" + JSON.stringify(items) + "}"
    

    Keep in mind that you need to send a JSON string to ASP.NET AJAX. If you specify an actual JSON object as jQuery's data parameter, it will serialize it as &k=v?k=v pairs instead.

    It looks like you've read it already, but take another look at my example of using a JavaScript DTO with jQuery, JSON.stringify, and ASP.NET AJAX. It covers everything you need to make this work.

    Note: You should never use JavaScriptSerializer to manually deserialize JSON in a "ScriptService" (as suggested by someone else). It automatically does this for you, based on the specified types of the parameters to your method. If you find yourself doing that, you are doing it wrong.

    0 讨论(0)
  • 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)
        {
    
    0 讨论(0)
  • 2020-12-05 01:44

    see link http://www.andrewrowland.com/article/display/consume-dot-net-web-service-with-jquery

    0 讨论(0)
提交回复
热议问题