3

How can I receive a JSON as a model (contains a dictionary) in a MVC 3 action?

Browser side: Post a JSON to a MVC3 action:

UpdateData : 
{
   Id: 88991,
   Changes:
   {
      X:5,
      Y:6
   }
}

Server side:

public class UpdateDataModel
{
    public int Id {get;set;}
    public IDictionary<string, string> Changes {get;set;}
}

public ActionResult SaveUpdateData(UpdateDataModel updateData)
{
    // updateData.Id should be 88991
    // updateData.Changes should be a dictionary containing X:5, Y:6
}
Zach
  • 5,715
  • 12
  • 47
  • 62

2 Answers2

3

I think it should be like this:

UpdateData : 
{
   Id: 88991,
   Changes:
   [
      { Key: 'X', Value: 5 },
      { Key: 'Y', Value: 6 }
   ]
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117
1

I typically do this by POSTing back to the server via ajax with jQuery in combination with the JSON library.

Your json posted back to the server needs to correctly match the properties in your server side model so that the default model binder in MVC can figure out what to map it to. Your controller action/route would be just fine, here is what it would look like client-side:

    function Save()
    {
        var data = {
            updateData: {
                Id: 85,
                Changes: [
                    { Key: 'A', Value: 'B' },
                    { Key: 'C', Value: 'D' },
                ]
             }
        };

        $.ajax({
            type: 'POST',
            url: '/someController/SaveUpdateData',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(data),
            success: function(response) {
                //do stuff here after finishing server side
            }
        });
    }

jQuery Library

JSON Library

Matthew Cox
  • 13,566
  • 9
  • 54
  • 72