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<string, object>.

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?

0

3 Answers 3

2

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) {...}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.