使用JsonValueProviderFactory绑定非原始类型

时间:2011-04-02 06:05:17

标签: json asp.net-mvc-2

我将json发送到HttpPost Rest API

[HttpPut]
[ActionName("Device")]
public ActionResult PutDevice(Device d)
{
   return Content("");
}

Json发送的是

{
"Name":"Pen",
"Type":1,
"DeviceSize":{"Width":190,"Height":180}
}

设备定义如下:

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

问题是名称和JsonValueProviderFactory正确绑定了Type。但是类型为Size的DeviceSize没有绑定,并且始终为空。

我错过了什么?

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

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

感谢。请帮忙。

1 个答案:

答案 0 :(得分: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; }
}

控制器:

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

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

查看(~/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>
Application_Start中的

Global.asax方法:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

JsonValueProviderFactory课程取自Microsoft.Web.Mvc大会。