使用JsonValueProviderFactory绑定非原始类型

Gau*_*ain 0 json asp.net-mvc-2

我将json发送到HttpPost Rest API

[HttpPut]
[ActionName("Device")]
public ActionResult PutDevice(Device d)
{
   return Content("");
}
Run Code Online (Sandbox Code Playgroud)

Json发送的是

{
"Name":"Pen",
"Type":1,
"DeviceSize":{"Width":190,"Height":180}
}
Run Code Online (Sandbox Code Playgroud)

设备定义如下:

public class Device
{
   public string Name {get; set;}
   public int Type {get; set;}
   public Size DeviceSize {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

问题是Name和Type都被JsonValueProviderFactory正确绑定.但是类型为Size的DeviceSize没有绑定,并且始终为空.

我错过了什么?

我有其他类似的Point,Color等类型的属性.所有这些也没有正确绑定.

我已经在Global.asax.cs的Application_Start中添加了JsonValueProviderFactory

谢谢.请帮忙.

Dar*_*rov 7

由于您只显示了部分代码,因此很难回答您的问题.这是一个完整的工作示例:

模型:

public class Device
{
    public string Name { get; set; }
    public int Type { get; set; }
    public Size DeviceSize { get; set; }
}

public class Size
{
    public int Width { get; set; }
    public int Height { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPut]
    [ActionName("Device")]
    public ActionResult PutDevice(Device d)
    {
        return Content("success", "text/plain");
    }
}
Run Code Online (Sandbox Code Playgroud)

查看(~/Views/Home/Index.aspx):

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery-1.4.1.js") %>"></script>
<script type="text/javascript">
    $.ajax({
        url: '<%= Url.Action("Device") %>',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
            Name: 'Pen',
            Type: 1,
            DeviceSize: { 
                Width: 190, 
                Height: 180 
            }
        }),
        success: function (result) {
            alert(result);
        }
    });
</script>

</asp:Content>
Run Code Online (Sandbox Code Playgroud)

Application_Start方法Global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
Run Code Online (Sandbox Code Playgroud)

JsonValueProviderFactory班是从拍摄Microsoft.Web.Mvc组装.