0

Here is how I call the method:

{"email":"xxx@hotmail.com","json":{"some1":"some1", "id":1},"yyy":"yyy"}

And my method has these parameters:

MyMethod(string email, Dictionary<string, object> json, string timestamp){...}

And when I call it with the above mentioned parameters, the method is being called but 'json' doesn't contain nothing. Its count is 0. Why is this happening? How to solve it?

petko_stankoski
  • 10,459
  • 41
  • 127
  • 231

1 Answers1

1

The default JSON serializer does not support this out of the box, however JSON.NET and the System.Web.Script.Serialization.JavaScriptSerializer support this, check the answers to a similar question:
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

JSON.NET will be the default json serializer for ASP.NET 4.5 WebAPI, so you can expect it to be shipped with ASP.NET + get support from MS for it.

UPDATE
In order to let ASP.NET bind the model properly you need a custom model binder:

 public class DictionaryModelBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      var serializer = new JavaScriptSerializer();
      var value = controllerContext.RequestContext.HttpContext.Request.Form["json"];
      return serializer.Deserialize<Dictionary<string, object>>(HttpUtility.UrlDecode(value));
    }
  }

And add the new model binder to the Application model binders in the Application_Start method:

  protected void Application_Start()
  {          
    ModelBinders.Binders.Add(typeof (Dictionary<string, object>), new DictionaryModelBinder());
    RegisterRoutes(RouteTable.Routes);
  }
Community
  • 1
  • 1
ntziolis
  • 10,091
  • 1
  • 34
  • 50