Reputation: 45
If I understand the Binding of posted JSon data to an action's parameter in asp.net mvc 3, I have nothing special to do.
For example :
[HttpPost]
public JsonResult Synchro(TestJSON data)
{
... data member should contain the JSon data sent...
return Json("ok" );
}
The TestJSON class :
public class TestJSON
{
public string chaine;
public int nombre;
}
and JSon data :
{chaine:"Test",nombre:"23"}
(sent with curl.exe for testing)
But data members are allway null or 0 in Syncho function.
I've searched a lot and I can't understand.
I found something strange. If I remove the JsonValueProviderFactory (in Application_Start) :
var v = ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().First();
ValueProviderFactories.Factories.Remove(v);
and if I create my own model binder (found somewhere on the bet) :
public class JeanJsonModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
var request = controllerContext.HttpContext.Request;
var incomingData = new StreamReader(request.InputStream).ReadToEnd();
if (String.IsNullOrEmpty(incomingData))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize(incomingData, bindingContext.ModelType);
}
}
and if I manually bind my parameter :
[HttpPost]
public JsonResult Synchro([ModelBinder(typeof(JeanJsonModelBinder))] TestJSON data)
{
... data member should contains JSon data sent...
return Json("ok" );
}
It works !
Any idea ?
Thanks
Upvotes: 0
Views: 826
Reputation: 20180
Try using properties for your model class instead of datamembers. I think that if you replace the default model binder with yours it might work to but you should still use propertys because this is the standard mo.
Upvotes: 2