【问题标题】:jQuery 1.5 Pass strings and an object to a .NET page methodjQuery 1.5 将字符串和对象传递给 .NET 页面方法
【发布时间】:2011-03-08 15:38:47
【问题描述】:

我已将代码简化为仅传递数组,但仍然没有任何运气
当我单步执行代码并到达 ajax 请求的要点时

jsonText 包含:

[{"UserId":"8"},{"UserId":"9"},{"UserId":"5"},{"UserId":"13"},{"UserId":"6"},{"UserId":"11"}]  

jsonTextSerialized contains:  
"[{\"UserId\":\"8\"},{\"UserId\":\"9\"},{\"UserId\":\"5\"},{\"UserId\":\"13\"},{\"UserId\":\"6\"},{\"UserId\":\"11\"}]"  




function GetUserSchedules() {  
 var jsonText = $.toJSON(arrParams);  
  var jsonTextSerialized = Sys.Serialization.JavaScriptSerializer.serialize(jsonText);  
  $.ajax({  
    type: "POST",  
    url: "/myurl/jquery.aspx/GenerateUserSchedules",  
    data: "{'data':'" + jsonTextSerialized + "'}",  
    contentType: "application/json",  
    dataType: "json",  
    success: function () { alert('Made It!'); },  
    error: function (result) { alert(Failed: ' + result.responseText);   
  });  

我后面的代码有

[Serializable]  
public class User  
{  
  public int UserId { get; set; }  
}  

[System.Web.Script.Services.ScriptMethod]  
[System.Web.Services.WebMethod]  
public static void GenerateUserSchedules(User[] data)  
{  
  //do stuff  
} 

响应文本是:
"处理请求时出错。","StackTrace":"","ExceptionType":""}

我做错了什么?

在您的帮助下我的解决方案:

感谢大家的努力。我无法表达对您的所有投入的感激之情。我很尴尬地承认这一点,但我已经坚持了好几天了。

我从您的所有回答中看到,有多种方法可以解决此问题。 我最喜欢 JSON.stringify 解决方案有两个原因:

  1. 它消除了疏忽的危险 当我将参数添加到 阿贾克斯请求。
  2. 根据 Oleg 的说法,它 是一种更有效的序列化方式 数据对象

这就是我决定解决问题的方法。

<script type="text/javascript">        
    var startDate;
    var endDate;
    var ddlViewSelectedItem;
    var ddlViewSelectedValue;
    var ddlOrgSelectedValue;
    var arrUsers= [];



    $(document).ready(function () {
        ddlViewSelectedItem = $('#<%=ddlView.ClientID %> option:selected').text();
        ddlViewSelectedValue = $('#<%=ddlView.ClientID %> option:selected').val();
        ddlOrgSelectedValue = $('#<%=ddlOrganization.ClientID %> option:selected').val();

        $.when(GetStartDate(), GetEndDate()) //these populate strt and end dates
            .then(function () {
                GetUserIDs();       // populates arrUsers
                GetUserSchedules();                                    
            })
            .fail(function () {
                failureAlertMsg();

            })
    });

    // Here I use JSON.stringify because it simplifies adding params. No messy single and/or double quote confusion. I love this. Must include json2.js from https://github.com/douglascrockford/JSON-js/blob/master/json2.js
    function GetUserSchedules() { 
        var jsonTextStringified = JSON.stringify({ data: arrParams, startDate: startDate, endDate: endDate, ddlViewSelectedItem: ddlViewSelectedItem, ddlViewSelectedValue: ddlViewSelectedValue, ddlOrgSelectedValue: ddlOrgSelectedValue }); 
        $.ajax({
            type: "POST",
            url: "/myurl/jquery.aspx/GenerateUserSchedules", // this is a call to a pagemethod, not a webservice, so .aspx is correct
            data: jsonTextStringified,
            contentType: "application/json",
            dataType: "json",
            success: function () { alert('Sweet! Made It!'); }
            ,
            error: function (result) { alert('Failed!: ' + result.responseText); }
        });
    }

后面的代码:

[Serializable]
public class User
{
    public string UserId { get; set; }
}


[System.Web.Script.Services.ScriptMethod]
[System.Web.Services.WebMethod]
public static void GenerateUserSchedules(User[] data, string startDate, string endDate, string ddlViewSelectedItem, string ddlViewSelectedValue, string ddlOrgSelectedValue)
{
    //do cool stuff and eventually send data back
}

再次感谢大家的帮助

【问题讨论】:

    标签: c# jquery json deserialization


    【解决方案1】:

    查看答案hereherehere。很多人都犯了同样的错误。

    1. 在 JavaScript 对象的初始化中,您可以同时使用引号和双引号,但在 JSON 数据中只允许使用双引号。
    2. 你不应该像{"{'startDate':'" + startDate + "', ...那样制作JSON序列化手册,也不要使用旧的$.toJSON jQuery插件。最好的方法是使用json2.js 中的JSON.stringify 函数。最新版本的网络浏览器支持本机代码中的功能,因此运行速度非常快。

    另一件看起来很奇怪的事情是路径“/myurl/jquery.aspx/GenerateUserSchedules”而不是“/myurl/jquery.asmx/GenerateUserSchedules”(asmx 而不是 aspx)。

    在你的情况下,你应该使用

    data: JSON.stringify({
        startDate: startDate,
        endDate: endDate,
        ddlViewSelectedItem: ddlViewSelectedItem,
        ddlViewSelectedValue: ddlViewSelectedValue,
        ddlOrgSelectedValue: ddlOrgSelectedValue
    })
    

    如果使用type: "POST"

    data: {
        startDate: JSON.stringify(startDate),
        endDate: JSON.stringify(endDate),
        ddlViewSelectedItem: JSON.stringify(ddlViewSelectedItem),
        ddlViewSelectedValue: JSON.stringify(ddlViewSelectedValue),
        ddlOrgSelectedValue: JSON.stringify(ddlOrgSelectedValue)
    }
    

    如果您决定使用type: "GET"

    为 web 方法的所有输入参数发送数据很重要。至少您应该发送带有null 值的参数作为输入(对于可为空的对象)。

    更新:当时你重写了你的问题。所以现在回答新版本的问题。

    你应该使用

    $.ajax({  
        type: "POST",  
        url: "/myurl/jquery.aspx/GenerateUserSchedules",  
        data: JSON.stringify({data: [
                {UserId:8},{UserId:9},{UserId:5},{UserId:13},{UserId:6},{UserId:11}]}),  
        contentType: "application/json",  
        dataType: "json",  
        success: function () { alert('Made It!'); },  
        error: function (result) { alert(Failed: ' + result.responseText);   
    });
    

    原因很简单。因为您有带有data 输入参数的方法GenerateUserSchedules(User[] data),所以您应该使用JSON.stringify({data: yourData}) 作为输入。 User 对象的数组应该是包含 {UserId:8}(或 {'UserId':8}{"UserId":8})项的数组,但不是 {UserId:"8"}

    【讨论】:

    • @Oleg,感谢您的回复。当我尝试使用 JSON.stringify 时,我收到一条错误消息,提示“JSON 未定义”我在我的页面中包含了 json-2.2.js
    • @Bengal:我不知道json-2.2.js 文件。我只知道 json2.js。对于第一个测试,您可以使用$.toJSON 而不是JSON.stringify,但JSON.stringify 更好。对于下一个实验,您可以将来自 here 的 json2.js 包含为 &lt;script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/json2.js"&gt;&lt;/script&gt;
    • @Bengal:我用github.com/douglascrockford/JSON-js的最新版本(2011-02-23)更新了文件ok-soft-gmbh.com/jqGrid/json2.js
    • @Oleg,只是好奇,为什么'JSON.stringify 更好'?
    • @Bengal:首先,代码由JSON格式的作者Douglas Crockford编写。第二个在代码中你可以看到if (!JSON) { JSON = {}; }等等。我的意思是如果JSON 类已经存在(本机Web 浏览器实现)并且JSON.stringify 也存在,那么JSON-js 不要覆盖代码,您将使用本机非常快速的函数实现。另一边的$.toJSON 将被实现为 JavaScript 代码,并且是缓慢的。
    【解决方案2】:

    有几种方法可以做到这一点。如果您的应用程序使用 MS Ajax 库,那么您需要在客户端做的就是

    var jsonText = [{"UserId":"8"},{"UserId":"9"},{"UserId":"5"}];
    var jsonTextSerialized = Sys.Serialization.JavaScriptSerializer.serialize(jsonText);
    

    然后您可以将此 jsonTextSerialized 与您必须将其发送到服务器端代码的其他参数一起使用。在服务器端,您可以拥有

    public class User{
      public Int32 UserId{
        get;set;
      }
    }
    [System.Web.Script.Services.ScriptMethod]  
        [System.Web.Services.WebMethod]  
        public static void GenerateUserSchedules(string startDate, string endDate, string ddlViewSelectedItem, string ddlViewSelectedValue, string ddlOrgSelectedValue, User[] customObejct) 
    

    这应该会自动为您完成。

    如果你没有使用 MS Ajax,那么从这里获取 JSON2.js

    http://www.json.org/js.html

    您可以使用此库在客户端序列化您的对象。在服务器端,事情应该保持不变。

    如需更详细的指南和信息,请查看此

    http://forums.asp.net/t/1388935.aspx

    希望这会有所帮助!

    尼基尔

    您的自定义对象现在应该具有对象

    【讨论】:

    • @Nikhil,感谢您的回复。我已经听从了你的建议,并相应地编辑了原始问题,但仍然不完全在那里。您还有什么建议吗?
    • 您在 .NET 端的公共类有 UserID 而不是 UserId。在序列化时,这些小事情很重要。请尝试使用 UserId!
    • @Nikhil,再次感谢您的回复。我确实按照您的规定进行了编辑,但仍然没有运气
    • 我同时尝试了一些东西。您能否尝试从您的 javascript 对象中删除双引号?所以将数据设为 [{UserId:8},{UserId:9}]....... 而不是 [{"UserId":8"}...]
    • 如果我更改 User 类并将 UserId 设为字符串,这样就足够了吗?我问是因为我必须填充 ArrItems 的函数是一个从表中获取值的 foreach 循环,所以我无法控制如何保存“8”
    【解决方案3】:

    可以这么简单:

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

    改成

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

    AND/OR 将客户端 "UserId" 更改为 "UserID"

    【讨论】:

      【解决方案4】:

      确保 json 属性名称和类型与 Web 方法参数匹配。 您的 jsonText 变量是一个数组,因此 Web 方法需要一个数组类型的属性来接受它(就像 Nikhil 发布的示例一样)。

      因此,如果您在 Nikhil 的示例中使用 Web 方法签名和自定义用户对象,则需要将 jquery ajax 调用的 data 属性设置为:

      "{'startDate':'" + startDate + "', 'endDate':'" + endDate + "', 'ddlViewSelectedItem':'" + ddlViewSelectedItem + "', 'ddlViewSelectedValue':'" + ddlViewSelectedValue + "', 'ddlOrgSelectedValue':'" + ddlOrgSelectedValue + "','customObejct':" + jsonText + "}"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-05
        • 2010-09-20
        • 2013-01-21
        • 1970-01-01
        • 2021-09-20
        • 2013-01-10
        • 2012-04-14
        • 1970-01-01
        相关资源
        最近更新 更多