HttpPost Rest APIにjsonを送ります
[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;}
}
問題は、NameとTypeの両方がJsonValueProviderFactoryによって正しくバインドされていることです。しかし、Size型のDeviceSizeはバインドされておらず、常に空です。
私は何が欠けていますか?
私はポイント、色などのタイプの他の同様のプロパティを持っています。それらすべてもまた正しくバインドされていません。
Global.asax.csのApplication_StartにJsonValueProviderFactoryを追加しました
ありがとう。助けてください。
回答:
回答№1の場合は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 アセンブリ。