MVC 4通过POST数据发送json对象

时间:2014-04-14 20:20:23

标签: asp.net-mvc-4 asp.net-web-api

我从客户端发送JSON对象但是当我得到我的模型时,所有属性都绑定了默认值。

我尝试了一些方法,例如我将数据作为字符串但没有预期的结果。 那我怎么解决这个问题呢?

Web API配置

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    var json = config.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    config.Formatters.Remove(config.Formatters.XmlFormatter);
}

模型

[Serializable]
public class WorkerPuantaj
{
    public int workT { get; set; }
    public int PDay { get; set; }
    public int PMonth { get; set; }
    public int PYear { get; set; }
    public int worker { get; set; }
}

客户请求

$.ajax({
       url: "/api/BuildingApi/AddPuantajItems",
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       type: 'POST',
       data: JSON.stringify(jsonData),
       success: function (data) {
           alert("oldu");
       },
       error: function (a, b, c) {
           alert("olmadı");
       }
   });

JSON正在发送

  

" [{" workT":1," PDAY":20," PMonth&#34:4," PYear"日期:2014年,"工人":3},{" workT":2" PDAY":21," PMonth&#34:4 " PYear":2014,"工人":3},{" workT":3," PDAY":22,&#34 ; PMonth&#34:4," PYear":2014,"工人":3}]

Debugger Display

1 个答案:

答案 0 :(得分:1)

由于您将数据作为JSON数组发送,因此在方法" AddPuantajItems"你应该把你的参数作为WorkerPuantaj [],但这不是你遇到问题的原因。

如果在MVC Web API模型上使用Serializeable属性,则无法将传入的JSON数据反序列化为模型类型。我不知道原因,但它解决了我的测试用例的问题。

删除[Serializable]关键字并告诉我它是否已修复。

相关问题