发布数据未按预期填充模型

时间:2015-11-04 15:42:01

标签: asp.net ajax asp.net-web-api

我有一个Web表单,它向我的一个控制器提交ajax请求。请求如下所示:

已析

CustomerId:2937
models:{"OriginalDate":"2015-08-12T17:06:37.25","BatteryName":"Briggs B-2H and 3H Water Tank","DeviceName":"Briggs B2-B3 - Water Tank 5","Date":"2015-08-11T22:06:00.000Z"}

原始

CustomerId=2937&models=%7B%22OriginalDate%22%3A%222015-08-12T17%3A06%3A37.25%22%2C%22BatteryName%22%3A%22Briggs+B-2H+and+3H+Water+Tank%22%2C%22DeviceName%22%3A%22Briggs+B2-B3+-+Water+Tank+5%22%2C%22Date%22%3A%222015-08-11T22%3A06%3A00.000Z%22%7D

我的控制器方法如下:

    [Route("Update")]
    [HttpPost]
    public IHttpActionResult Update(UpdateQuery model)
    {
        try
        {
            ...
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    public class UpdateQuery
    {
        public int CustomerId { get; set; }
        public EventModel models { get; set; }
    }

    public class EventModel
    {
        public string OriginalDate { get; set; }
        public string BatteryName { get; set; }
        public string DeviceName { get; set; }
        public string Date { get; set; }
    }

当请求进入时,CustomerId字段将被填充而没有任何问题,但"模型"部分没有。

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:1)

如果你发送这样的有效JSON,它应该可以工作。

{
    "CustomerId": "2937",
    "models": {
        "OriginalDate": "2015-08-12T17:06:37.25",
        "BatteryName": "Briggs B-2H and 3H Water Tank",
        "DeviceName": "Briggs B2-B3 - Water Tank 5",
        "Date": "2015-08-11T22:06:00.000Z"
    }
}

Web api模型绑定会将此Json结构转换为您的模型,UpdateQuery的实例。

构建此JSON结构并使用jQuery

发送到端点的示例代码
var data = {models : {}};
data.CustomerId = 234233;
data.models.OriginalDate = "2015-08-12T17:06:37.25";
data.models.BatteryName = "Briggs B-2H and 3H Water Tank";
data.models.DeviceName = "Briggs B2-B3 - Water Tank 5";
data.models.Date = "2015-08-11T22:06:00.000Z";


$.post(yourApiEndPointUrlHere, data, function(res) {
    console.log(res);
});