0

I have simplified my code to just passing the array but still am not having any luck
When I step through the code and get to the point of the ajax request

jsonText contains:

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

and

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);   
  });  

My code behind has

[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  
} 

The responseText is:
"There was an error processing the request.","StackTrace":"","ExceptionType":""}

What am I doing wrong?

MY SOLUTION WITH YOUR HELP:

Thank you all for your efforts. I can't express how grateful for all your input. I am embarassed to admit it, but I had been stuck on this for days.

I see from all your answers that there are various ways to approach this. I like the JSON.stringify solution best for two reasons:

  1. It removes the danger of inadvertant typos when I add parameters to the ajax request.
  2. According to Oleg, it is a more efficient way to serialize the data objects

So here is how I decided to resolve the issue.

<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); }
        });
    }

Code behind:

[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
}

Thank you again for all your help

Bengal
  • 329
  • 4
  • 21

4 Answers4

1

There are a couple of approaches to do this. If your application uses MS Ajax libraries by any chance then all you need to do on client side is

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

You can then use this jsonTextSerialized with other parameters that you have to send it to your server side code. On server side you can have

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) 

This should automatically do it for you.

If you are not using MS Ajax, then get JSON2.js from here

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

You can use this library to serialize your object on client side. On server side things should remain the same.

For more detailed guide and information also check this out

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

Hope this helps!

Nikhil

your custom object should now have the object

Nikhil
  • 3,304
  • 1
  • 25
  • 42
  • @Nikhil, thank you for your response. I have followed you suggestion and have edited the original question accordingly but am still not quite there. Do you have any more suggestions? – Bengal Mar 08 '11 at 16:29
  • Your public class on .NET side has UserID instead of UserId. While serializing, these small things matter. Try with UserId please! – Nikhil Mar 08 '11 at 16:59
  • @Nikhil, thank you for your response again. I did make the edit as you prescribed but still no luck – Bengal Mar 08 '11 at 17:33
  • I experimented with a few things meanwhile. Can you please try removing double quotes from your javascript object? So have data it as [{UserId:8},{UserId:9}]....... and not as [{"UserId":8"}...] – Nikhil Mar 08 '11 at 17:39
  • How about if I change the User class and make UserId a string, would that be sufficient? I ask because the function I have to populate the ArrItems, is a foreach loop that grabs values from a table, so I don't have control of how the "8" is saved – Bengal Mar 08 '11 at 17:53
  • Ah, that did it. I changed the UserId to a string in the class and it successfully passed the array of objects. I'll update my code shortly to show the working version – Bengal Mar 08 '11 at 17:57
1

Make sure the json property names and types matchup with the web method parameters. Your jsonText variable is an array and so the Web method needs a property of an array type to accept it (like in the example Nikhil posted).

So if you were using the web method signature in Nikhil's example and the custom user object, you would need to make the data property for the jquery ajax call to be:

"{'startDate':'" + startDate + "', 'endDate':'" + endDate + "', 'ddlViewSelectedItem':'" + ddlViewSelectedItem + "', 'ddlViewSelectedValue':'" + ddlViewSelectedValue + "', 'ddlOrgSelectedValue':'" + ddlOrgSelectedValue + "','customObejct':" + jsonText + "}"
Matt27
  • 325
  • 5
  • 14
1

could it be as simple as:

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

change to

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

AND/OR change client side "UserId" to "UserID"

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
1

Look at the close answer here, here or here. Many people made the same errors.

  1. In the initialization of JavaScript objects you can use both quotes and double quotes, but in the JSON data only double quotes are permitted.
  2. You should no time make JSON serialization manual like {"{'startDate':'" + startDate + "', ... and not use old $.toJSON jQuery plugin. The best way is to use JSON.stringify function from the json2.js. The most current version of the web browsers support the function in the native code, so it work very quickly.

One more thing which look strange is the path "/myurl/jquery.aspx/GenerateUserSchedules" instead of "/myurl/jquery.asmx/GenerateUserSchedules" (asmx instead of aspx).

In your case you should use

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

in case of usage of type: "POST" and

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

if you decide to use type: "GET".

It is important to send data for all input parameters of the web method. At least you should send parameters with the null value as the input (for nullable objects).

UPDATED: At the time you rewrote your question. So now the answer on the new version of your question.

You should use

$.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);   
});

The reason is easy. Because you have the method GenerateUserSchedules(User[] data) with the data input parameter you should use JSON.stringify({data: yourData}) as the input. The array of User objects should be array with the items {UserId:8} (or {'UserId':8} or {"UserId":8}), but not {UserId:"8"}.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • @Oleg, thnak you for you responses. When I try to use JSON.stringify I get an error that says 'JSON is undefined' I have included json-2.2.js in my page – Bengal Mar 08 '11 at 17:50
  • @Bengal: I don't know `json-2.2.js` file. I know only json2.js. For the first test you can use `$.toJSON` instead of `JSON.stringify`, but `JSON.stringify` is better. For the next experiment you can include json2.js from [here](http://www.ok-soft-gmbh.com/jqGrid/json2.js) as `` – Oleg Mar 08 '11 at 17:58
  • @Bengal: I updated the file http://www.ok-soft-gmbh.com/jqGrid/json2.js with the last version (2011-02-23) from https://github.com/douglascrockford/JSON-js – Oleg Mar 08 '11 at 18:17
  • @Oleg, Just curious, why is 'JSON.stringify is better'? – Bengal Mar 08 '11 at 19:25
  • @Bengal: First of all, the code is written by Douglas Crockford, the author of JSON format. Second in the code you can see `if (!JSON) { JSON = {}; }` and so on. I mean if `JSON` class already exist (the native web browser implementation) and the `JSON.stringify` also exist, then `JSON-js` don't overwrite the code and you will use the native very quick implementation of the function. The `$.toJSON` on the other side will be implemented as JavaScript code and is slowly. – Oleg Mar 08 '11 at 20:20
  • @Bengal: One more small remark. I seen that you has **0 Votes** in your profile, so you didn't use voting of any answer or another question. You say other people thanks for the help, but it would be better if you vote the answers up. Starting with 15 reputation points you have right to vote up any answer or question (excepting youth one). [Here](http://stackoverflow.com/faq#howtoask) you can read the simple rule: "As you see new answers to your question, vote up the helpful ones by clicking the upward pointing arrow to the left of the answer." I recommend you to follow the rule. It helps all. – Oleg Mar 08 '11 at 20:51
  • Ah, OK, I see. I am pretty new to this community so I am not sure how it all works. Thanks for pointing this out to me, and for the answer regarding the stringify question. 'preciate it. – Bengal Mar 08 '11 at 20:55
  • @Bengal: I have seen that you are polite to the answer and I was sure that you just don't know about the voting. Only because of that I wrote you. I wish you all the best and enjoying the time on the stackoverflow. – Oleg Mar 08 '11 at 21:01