Skip to main content
 首页 » 编程设计

c#之传递给 WebApi 的 JQuery 值始终为空

2024年02月20日25zhujiabin

我在使用 Web Api 时遇到问题,希望这里有人可以帮助我。

我有一个 jQuery 方法如下......

    function OnInsert(evt) { 
        var truckId = $("#txtTruckId").val(); 
        var truckReg = $("#txtTruckReg").val(); 
        var description = $("#txtDescription").val(); 
        var condition = $("#txtCondition").val(); 
        var data = '{"obj":{"TruckId":"' + truckId + '","Reg":"' + truckReg + 
                   '","Description":"' + description + '","Condition":"' + condition + '"}}'; 
        var json = JSON.stringify(data) 
 
        $.ajax({ 
            url: '/api/Values', 
            cache: false, 
            type: 'POST', 
            data: json, 
            dataType: 'json', 
            success: function (results) { 
                $("#txtTruckId").val(''); 
                $("#txtTruckReg").val(''); 
                $("#txtDescription").val(''); 
                $("#txtCondition").val(''); 
                $.getJSON("api/Values", LoadCustomers); 
                alert('Truck Added !'); 
            } 
        }) 
    } 

当我调试“数据”变量成功捕获数据时。

然后我的 WebApi Controller 中有一个函数......

    // POST api/values 
    public void Post(TruckInfo obj) 
    { 
        WebApiTestEntities db = new WebApiTestEntities(); 
 
        db.TruckInfoes.Add(obj); 
        db.SaveChanges(); 
    } 

但是,当我调试时,所有参数都显示为空值。

我发现了这个:

http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html

其中指出我需要 Global.asax 中的以下代码行,但没有奏效。

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); 

我也发现了这个答案,但在尝试更改我的代码后,看起来他们编写的代码仍然无法正常工作。

jQuery posts null instead of JSON to ASP.NET Web API

有人能帮忙吗?

提前致谢

莱克斯

请您参考如下方法:

首先修复您的 JSON:

var data = { 
    truckId: truckId,  
    reg: truckReg,  
    description: description,  
    condition: condition 
}; 
var json = JSON.stringify(data); 

然后确保指定正确的内容类型请求 header :

$.ajax({ 
    url: '/api/Values', 
    type: 'POST', 
    contentType: 'application/json; charset=utf-8', 
    data: json, 
    success: function (results) { 
        $("#txtTruckId").val(''); 
        $("#txtTruckReg").val(''); 
        $("#txtDescription").val(''); 
        $("#txtCondition").val(''); 
        $.getJSON("api/Values", LoadCustomers); 
        alert('Truck Added !'); 
    } 
}); 

I found this:

http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html

Which states I need the following line of code in the Global.asax but that hasn't worked.

不,不,不。没有必要,只要您正确设置 JSON 请求的格式,Web API 就会将其绑定(bind)到您的模型。