0

我正在尝试使用 jQuery Ajax 将数据列表和变量发布到 WebApi。

我的客户端代码是:

var datatopost = new Object();
for(var i=0;i<results.length;i++)
{
    datatopost["[" + i + "].NodeID"] = results[i];
}
var result;
result = grandtotal;
$.ajax({
    type: "POST",
    url: createurl,
    dataType: "json",
    traditional: true,
    data: "{ 'node': '" + datatopost + "',ttl: '" + result + "'}",
    statusCode: {
        200: function () {
            alert("success");
        }
    },
    error:
        function (res) {
            alert('Error');
            $("#txtmsg").val("error" + " "
            + res.status + " " + res.statusText);
        }
});

我的服务器端代码是

public HttpResponseMessage PostBuy([FromBody]List<Node> node, decimal ttl)
{
   //Success code here
   return new HttpResponseMessage(HttpStatusCode.OK);
}

我在检查元素的网络选项卡中收到错误的请求错误。

我的代码有问题吗?

4

2 回答 2

0

这是我发布包含其他值的列表的方式,我发布了一个JSON.stringify字符串,

                    var o = {};
                    o.UserCode = userCode;
                    o.Role = role;
                    o.UserId = r.d;
                    o.Hotels = [];
                    $('#hotel-list li :checkbox:checked').each(function () {
                        var ctrl = $(this);
                        var h = {};
                        h.ChainId = ctrl.val();
                        h.ProjectId = ctrl.next().val();
                        h.CityId = ctrl.next().next().val();
                        o.Hotels.push(h);
                    });
                    $.post("/home/UpdateDataToDb/", { d: JSON.stringify(o) }, function (r) {

                        alert(r.Msg);
                    });

我的服务器端代码是这样的:

    [System.Web.Mvc.HttpPost]
    public JsonResult UpdateDataToDb(string d)
    {
        var jsonStr = d;

        var json = JsonConvert.DeserializeObject<QueryPostData>(jsonStr);
        //json.UserCode
        //json.Role
        //json.UserId
        foreach (var chain in json.Hotels)
        {
            //My code to handle list `Hotels`
        }
    }

QueryPostData

public class QueryPostData
{
    public string UserCode { get; set; }
    public string Role { get; set; }
    public string UserId { set; get; }
    public List<BriefChain> Hotels { get; set; }
}

public class BriefChain
{
    public string ChainId { get; set; }
    public string ProjectId { get; set; }
    public string CityId { get; set; }
}
于 2014-05-18T13:37:45.377 回答
0

我不完全确定,但它可能与 JSON 中的“节点”元素有关。它看起来是一个对象,而不是一个数组。验证数据是否以 JSON 格式正确发送。

于 2012-08-24T20:00:59.597 回答