2012-08-24 18 views
0

我想使用jQuery Ajax發佈數據和變量列表到WebApi。使用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); 
} 

我在檢查元件的網絡標籤接收錯誤請求錯誤。

我的代碼有問題嗎?

回答

0

我不完全確定,但它可能與您的JSON中的「node」元素有關。它看起來是一個對象而不是數組。驗證數據是否以其JSON格式正確發送。

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