tags:

views:

963

answers:

3

Hi everyone, I am following this link to build a Client side repeater.

According to the above link to retrive the value from a Json key-value pair we can use result[i].property,for example

for (var post in msg)
{     
    var x= msg[post].Date;
    alert(x);
}

Here x returns the date from Json string. When I am trying to use the same with my data, it always returns as undefined. I tried to pop up an alert(msg.d) that shows a nice Json string with all my data. But when I try msg[post].Date(property name) it's always returning undefined.

Please help..

Thanks in advance.

Update:

From the backend I am returning a generic list and then converting it into Json using the following code.

public static string ConvertToJSON(this object obj) {

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());    

    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string jsonobj = Encoding.Default.GetString(ms.ToArray());
    ms.Dispose();
    return jsonobj;
}

then I am appending the returned Json to a stringbuilder and returning it to the Jquery ajax method.The returned Json looks like a string , not an object and hence I am unable to get any value from Json key value pair..

+1  A: 

What about the message, if you add this to your ajax does that help?

dataFilter: function(data)
            {
                var msg;
                if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },

Note that you then process this as msg, not msg.d like so:

success: function(msg)
            {
                SaveSuccess(msg);
            },
Mark Schultheiss
A: 

Looks to me like you got an array of objects to begin with, using your sample the following works:

messages = [{"AnsNo":0,"Answer":"","Category":"Help Centre.Mortgages.Existing customers","ClickURL":null,"ID":7,"Question":"How do I re-mortgage to you?","RecNo":0,"ValidFrom":"\/Date(-62135596800000+0000)\/","ValidUntill":"\/Date(-62135596800000+0000)\/"}]

for(i in messages)
{
    message = messages[i];
    //Says "Help Centre.Mortgages.Existing customers"
    alert(message.Category)
    //To get all key/value pairs
    for(key in message)
    {
        //Alerts all key value pairs one by one
        alert("Key:" + key + ", Value:" + message[key]);
    }
}
Kristoffer S Hansen
+1  A: 

Update:

It sounds like you're doubly serializing the data on the server-side, returning a JSON string that gets serialized as JSON itself. When that reaches the client-side and jQuery deserializes the first layer of JSON automatically, you're still left with the JSON string you manually built.

You should return the List<T> as the return value of your service method and let the framework handle JSON serialization.

Original Answer:

Assuming the object is still contained in ASP.NET AJAX's ".d" wrapper, as you implied:

for (var post in msg.d) {     
  var x = msg.d[post].Date;

  alert(x);
}

Or, a traditional loop, which might be more straightforward:

for (var i = 0; i < msg.d.length; i++) {
  var x = msg.d[i].Date;

  alert(x);
}
Dave Ward
Thanks Dave,after reading your post I realized that I am double serializing the data.such a silly mistake.Now I'm able to read the value with msg.d[0].Date.But got another problem.basically in the code behind web method I have different conditions.Based on the condition different generic list(ex.faqs,recognitions etc) is returned to the Jquery ajax method.I do not understand how can I set the return type(generic list) for the Web method based on the condition using your solution.Previously I used to append the string returned from Converttojson to a stringbuilder and return.
kranthi
Use IEnumerable as the return type.
Dave Ward
Returning IEnumerable looks like a great idea.In my code I have some conditions which will have to retrive data from multiple generic lists.For example if a condition is satisfied I need to do the following.Recognitionfactory rf = new Recognitionfactory();Recognitions rs= rf.getBasicSearchRecognitions(searchtext); Answerfactory af = new Answerfactory();Answers ans = af.getBasicSearchAnswers(searchtext); In the above case I need to return both rs,ans(generic lists) upon satisfying a certain condition.how can I return both of them for one condition?
kranthi
Ofcourse,It is possible to return either ans or rs with ienumerable being the return type of the web method.how to handle returning both ans,rs
kranthi
An IEnumerable could contain a collection of IEnumerables.That sounds like it's going to be difficult to work with though. Are you sure you shouldn't refactor it into separate methods? Or, maybe use a common DTO class (e.g. SearchResults) and map the various possible results to a List<SearchResults>?
Dave Ward
Probably having a common DTO may be easiest solution for my situation.Could you please tell me ,is there way to refer to a value in the key value with index (for example,instead of referring as msg.d[0].Category ,can I refer to it as msg.d[0][0] if category is the 1st value in the json object)?
kranthi
You should be able to, yes. If you have a common search results DTO, you will be able to use its properties as keys.
Dave Ward