简体   繁体   English

使用 jQuery 将 JSON 对象成功发送到 ASP.NET WebMethod

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

I've been working on this for 3 hours and have given up.我已经为此工作了 3 个小时,然后放弃了。 I am simply trying to send data to an ASP.NET WebMethod, using jQuery.我只是想使用 jQuery 将数据发送到 ASP.NET WebMethod。 The data is basically a bunch of key/value pairs.数据基本上是一堆键/值对。 So I've tried to create an array and adding the pairs to that array.所以我尝试创建一个数组并将对添加到该数组。

My WebMethod (aspx.cs) looks like this (this may be wrong for what I'm building in JavaScript, I just don't know):我的 WebMethod (aspx.cs) 看起来像这样(这对于我用 JavaScript 构建的内容可能是错误的,我只是不知道):

[WebMethod]
public static string SaveRecord(List<object> items)
{
    ...
}

Here is my sample JavaScript:这是我的示例 JavaScript:

var items = new Array;

var data1 = { compId: "1", formId: "531" };
var data2 = { compId: "2", formId: "77" };
var data3 = { compId: "3", formId: "99" };
var data4 = { status: "2", statusId: "8" };
var data5 = { name: "Value", value: "myValue" };

items[0] = data1;
items[1] = data2;
items[2] = data3;
items[3] = data4;
items[4] = data5;

Here is my jQuery AJAX call:这是我的 jQuery AJAX 调用:

var options = {
    error: function(msg) {
        alert(msg.d);
    },
    type: "POST",
    url: "PackageList.aspx/SaveRecord",
    data: { 'items': items },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    success: function(response) {
        var results = response.d;
    }
};
jQuery.ajax(options);

I get the error:我收到错误:

Invalid JSON primitive: items.

So, if I do this:所以,如果我这样做:

var DTO = { 'items': items };

and set the data parameter like this:并像这样设置数据参数:

data: JSON.stringify(DTO)

Then I get this error:然后我得到这个错误:

Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1[System.Object]\u0027

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.请记住,您需要将 JSON 字符串发送到 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.如果您指定一个实际的 JSON 对象作为 jQuery 的数据参数,它会将其序列化为 &k=v?k=v 对。

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 .看起来您已经阅读过它,但请再看一下我将 JavaScript DTO 与 jQuery、JSON.stringify 和 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).注意:您永远不应该使用 JavaScriptSerializer 在“ScriptService”中手动反序列化 JSON(正如其他人所建议的)。 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.如果你发现自己这样做了,那你就做错了。

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.使用 AJAX.NET 时,我总是将输入参数设为一个普通的旧对象,然后使用 javascript 反序列化器将其转换为我想要的任何类型。 At least that way you can debug and see what type of object the web method in is recieving.至少这样你可以调试并查看 web 方法正在接收什么类型的对象。

You need to convert your object to a string when using jQuery使用 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);
        }
    }
}

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)
    {

Decorate your [WebMethod] with another attribute:用另一个属性装饰你的 [WebMethod] :

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

I believe this is in System.Web.Services.Scripting...我相信这是在 System.Web.Services.Scripting 中......

This is the way you define your data (JSON)这是您定义数据的方式 (JSON)

data: { 'items': items },

and the this the way it should be这是应该的方式

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

basically you are serializing the parameter.基本上你是在序列化参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM