views:

1162

answers:

3

Here's the situation: I would like to iterate through a table with input controls, collect up the values and then submit them to an ASP.Net PageMethod to save the data to the database. I have the collection all figured out, but am getting an error that the string can't be converted to a Dictionary.

So I end up with something like this being passed to a method with the below signature

[
{ 'id': '383840923', 'name': 'fred', 'car':'honda' },
{ 'id': '243', 'name': 'joe', 'car':'honda' },
{ 'id': '4323423', 'name': 'paul', 'car':'honda' },
{ 'id': '38384234230923', 'name': 'ted', 'car':'honda' },
]

public static bool SaveData(Dictionary<string, object>[] items) {...}

I know that I can pass whole class objects back and forth if properly declared and ASP.Net will handle the conversions for me, but I don't need the whole class being passed, only a couple of the properties.

Edit: I'm using Jquery to do the post back to the server.

What am I doing wrong here?

A: 

@Jared the passed object is a JSON array. You can use json sharp to process it on server side. Here is a nice post about converting json array to C#.

TheVillageIdiot
+1  A: 

ASP.NET AJAX will automatically deserialize that for you if you use a DTO. Something like this on the server-side would match the JSON array you're sending in:

public class PeopleAndCarsDTO
{
  public int id { get; set; }
  public string name { get; set; }
  public string car { get; set; }
}

public static bool SaveData(List<PeopleAndCarsDTO> items) {...}
Dave Ward
Yea, I think I've read most of your blog more than once today. Great help. That's what I was trying to avoid having to create, but I figured out what the problem was. I was wrapping the array in quotes before it was being posted so it was being treated as a string instead of an array. So I can get away with my custom array.
Jared
+1  A: 

I figured out what the problem was. I was wrapping the array in quotes before sending it in as part of the $.ajax call so it was being treated as a string instead of an array.

            $.ajax({
       type: "POST",
       url: "<%= Response.ApplyAppPathModifier(Request.Path) %>/UpdateAcademicItems",
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       data: "{'items': **'**" + $.toJSON(items) + "**'**}",
       success: function(data) {
        if(false != data.d) {
         alert('we did it');
        } else {
         alert ('flop');
        }
       },
       error: function() {
        alert('Failed to save Program Items');
       }
      });
Jared