0

I would like to bind submission of JSON like this

{
 "id": 1,
 "name": "bob",
 "phone": "(425) 882-8080"
}

to...

class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    public PhoneNumber Phone { get; set; }
}

where the PhoneNumber class is able to bind to the phone string in the JSON. The idea was the use a json.net custom converter like:

class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    [JsonConverter(typeof(PhoneNumberCoverter))]
    public PhoneNumber Phone { get; set; }
}

The problem is that MVC is not even trying to use the ReadJson method. Model.Phone == null.

I have tried a few things. Hoping that if I had implicit operative overrides to and from string for the PhoneNumber class, it may just do it automatically. Nope.

What is the correct way to customize model binding for this scenario?

Matt
  • 873
  • 1
  • 9
  • 24
  • 2
    The [answers here](http://stackoverflow.com/questions/14591750/asp-net-mvc4-setting-the-default-json-serializer) might be related to your issue –  Jan 24 '15 at 04:01

1 Answers1

1

I think you expect that when your action method like

public ActionResult Post(Model myModel)
{
  // you expect that myModel should has used JSonConverter and provide you data.
}

Above thing will not work as you expected and reason for this JsonConvertor attribute is specific Json.net and not MVC attribute so DefaultModelBinder will not consider that attribute to bind your data.

Possible correct and simple way to do (But not strongly type)

   public ActionResult Post(string jsonData)
   {
       // Now here use Json.net JsonConvert to deserialize string to object of Type Model.
   }

Another solution to is to build your own custom modelbinder and use Json.net inside that.

dotnetstep
  • 17,065
  • 5
  • 54
  • 72
  • I have never dealt with model binder. If it is that or just receive a string, I think I will give modelbinder a go. – Matt Jan 24 '15 at 03:45