2

I have - var JsonObj = []; and I pushed some data into that and send it to codebehind using JQuery.ajax() method. I am able to receive in a method which has parameter like this

[WebMethod]
public static void SaveInfo(List<Object> userEnteredDetails)
{
}

And i loop thru the collection to get the data something like this,

foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
}

The problem here is, I am receiving more than 10 items in the collecton. So i cannot read another property in my above for loop. Something like this,

foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
string city= details["city"] as string;
}

Firsttime city wil throw an error, and next time customername. Because item variable will have one variable at a time. How to read all the more than 10 records efficiently since we dont have property, but can read only through an indexer (details["customerName"]).

1
  • is there any particular reason why you are using object instead of a custom strong-typed DTO like Person, Employee etc? Commented Jul 12, 2012 at 10:55

4 Answers 4

3

Try this:

string name = String.Empty;
string city = String.Empty;
foreach (object item in userEnteredDetails)
{
 Dictionary<string, object> details = item as  Dictionary<string, object>;
if (details.ContainsKey("customerName"))
 name = details["customerName"] as string;
if (details.ContainsKey("city"))
 city= details["city"] as string;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can enumerate the details Dictionary.

foreach(var kvp in details)
  {
// do something with kvp.Key and kvp.Value
  }

EDIT: To get a one merged details dictionairy first, you can try this:

var details = list.Select(item => item as Dictionary<string, object>).SelectMany(d => d).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

1 Comment

If u want all of the data merged to one dictionairy, you can merge the individual items to a dictionairy first.
1

One thing you could have a type with fields in them mapping to the list of objects. While making the ajax call stringify the json object. In your web method recieve it as string. Use Json Deserializer and deserialize it to the type you have created.

Comments

1

Theres a very flexible json framework (JSON.NET) which could help with this, definitley worth considering if your doing a lot of work with JSON http://json.codeplex.com/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.