我想像这样绑定JSON的提交
{
"id": 1,
"name": "bob",
"phone": "(425) 882-8080"
}
至...
class Model
{
public int Id { get; set; }
public string Name { get; set; }
public PhoneNumber Phone { get; set; }
}
其中PhoneNumber类能够绑定到JSON中的电话字符串.这个想法是使用json.net自定义转换器,例如:
class Model
{
public int Id { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(PhoneNumberCoverter))]
public PhoneNumber Phone { get; set; }
}
问题在于MVC甚至没有尝试使用该ReadJson
方法.Model.Phone ==空.
我已经尝试了几件事.希望如果我在PhoneNumber类的字符串之间有隐式的操作性覆盖,它可能会自动执行.不.
针对这种情况自定义模型绑定的正确方法是什么?
我认为您希望当您的操作方法像
public ActionResult Post(Model myModel)
{
// you expect that myModel should has used JSonConverter and provide you data.
}
上面的事情不会按您预期的那样工作,并且此JsonConvertor属性的原因是特定的Json.net而不是MVC属性,因此DefaultModelBinder不会考虑该属性来绑定您的数据.
可能的正确而简单的操作方式(但不是强类型)
public ActionResult Post(string jsonData)
{
// Now here use Json.net JsonConvert to deserialize string to object of Type Model.
}
另一个解决方案是构建您自己的自定义modelbinder并在其中使用Json.net.
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?
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.
本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文