0

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

asked Apr 2, 2012 at 15:20

1 Answer 1

2

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.

answered Apr 2, 2012 at 15:30

2 Comments

You are right ! I feel a bit stupid, I spent some hours for nothing. Thank you very much !
Wonderful, dont feel stupid, everytime you fail is an opportunity to learn, the more you fail the better you get, at least, theoretically... Do feel free to mark your question as answered by clicking the button next to my post ;)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.