Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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) {...}

@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#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top