Wysyłam json do interfejsu API HttpPost Rest
[HttpPut]
[ActionName("Device")]
public ActionResult PutDevice(Device d)
{
return Content("");
}
Json wysłał to
{
"Name":"Pen",
"Type":1,
"DeviceSize":{"Width":190,"Height":180}
}
Urządzenie jest zdefiniowane jak poniżej:
public class Device
{
public string Name {get; set;}
public int Type {get; set;}
public Size DeviceSize {get; set;}
}
Problem polega na tym, że nazwa i typ są poprawnie powiązane przez JsonValueProviderFactory. Ale DeviceSize, który jest typu Rozmiar, nie jest związany i zawsze jest pusty.
czego mi brakuje?
Mam inne podobne właściwości typu Punkt, Kolor itp. NIE są one również poprawnie powiązane.
Dodałem już JsonValueProviderFactory w Application_Start Global.asax.cs
Dzięki. Proszę pomóż.
Odpowiedzi:
7 dla odpowiedzi № 1Trudno odpowiedzieć na twoje pytanie, ponieważ pokazałeś tylko części kodu. Oto pełny działający przykład:
Model:
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; }
}
Kontroler:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPut]
[ActionName("Device")]
public ActionResult PutDevice(Device d)
{
return Content("success", "text/plain");
}
}
Zobacz (~/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
metoda w Global.asax
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
The JsonValueProviderFactory
klasa została zaczerpnięta z Microsoft.Web.Mvc montaż.