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);
}

inspect 要素のネットワーク タブで不正なリクエスト エラーが表示されます。

私のコードに問題はありますか?

4

2 に答える 2

0

完全にはわかりませんが、JSON の「ノード」要素に関連している可能性があります。配列ではなくオブジェクトのようです。データが JSON 形式で適切に送信されていることを確認します。

于 2012-08-24T20:00:59.597 に答える
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 に答える