2013-01-11 22 views
5

Benim ajax çağrısı buSürekli MVC denetleyiciye jquery ajax yayında 400 (Bad Request) alıcı

$.ajax({ //actually approve or reject the promotion 
       url: url, 
       type: "POST", 
       data: '{'+data.PromotionId+','+data.UserId+','+data.ReasonText+'}', 
       dataType: "json", 
       //contentType: "application/json; charset=utf-8", 
       success: function (data) { 
        if (indicator == 'A') { 
         alert('Promotion approved successfully!'); 
        } 
        else { 
         alert('Promotion rejected successfully.'); 
        } 

        var homelink = '<%: Url.Action("Index","Home") %>'; 
        window.location.href = (homelink); 


        returndata = data; 
       }, 
       error: function (xhRequest, ErrorText, thrownError) { 
        alert("Failed to process promotion correctly, please try again"); 
        console.log('xhRequest: ' + xhRequest + "\n"); 
        console.log('ErrorText: ' + ErrorText + "\n"); 
        console.log('thrownError: ' + thrownError + "\n"); 
       } 
      }); 

benziyor Ve benim MVC denetleyicisi şöyle görünür: Ben sözdizimi düşünmüştü

[HttpPost] 
    public HttpResponseMessage ApprovePromotion(PromotionDecision decision) 
    { 
     if (ModelState.IsValid && decision != null) 
     { 
      bool status = PromotionBo.ApprovePromotion(decision); 
      if (status == true) 
       return new HttpResponseMessage(HttpStatusCode.OK); 
     } 
     return new HttpResponseMessage(HttpStatusCode.BadRequest); 
    } 

her ikisinde de doğruydu ama ajax çağrısını her yaptığımda 400 yanıt aldım. Ben yanlış yapıyorum nedir?

cevap

10

Sunucuya tamamen bozuk ve geçersiz bir JSON dizesi gönderiyorsunuz. Denetleyici eyleminin onu reddetmesi normaldir. Buna ek olarak, bir JSON isteğini göndermek istediğinizi belirten contentType parametresini de eklediniz.

Yani burada isteği yapmak için doğru yolu şudur: Ben JSON sunucuya gönderilen sağlamak için doğal olarak entegre olduğunda modern tarayıcılarda JSON.stringify yöntemi kullanıyorum nasıl

$.ajax({ //actually approve or reject the promotion 
    url: url, 
    type: "POST", 
    data: JSON.stringify({ 
     // Those property names must match the property names of your PromotionDecision view model 
     promotionId: data.PromotionId, 
     userId: data.UserId, 
     reasonText: data.ReasonText 
    }), 
    contentType: "application/json; charset=utf-8", 
    success: function (data) { 
     if (indicator == 'A') { 
      alert('Promotion approved successfully!'); 
     } 
     else { 
      alert('Promotion rejected successfully.'); 
     } 

     var homelink = '<%: Url.Action("Index","Home") %>'; 
     window.location.href = (homelink); 

     returndata = data; 
    }, 
    error: function (xhRequest, ErrorText, thrownError) { 
     alert("Failed to process promotion correctly, please try again"); 
     console.log('xhRequest: ' + xhRequest + "\n"); 
     console.log('ErrorText: ' + ErrorText + "\n"); 
     console.log('thrownError: ' + thrownError + "\n"); 
    } 
}); 

Bildirim doğru ve tüm değerler düzgün bir şekilde kodlanmıştır. Ayrıca, tarayıcıları taş devresinden desteklemeniz gerekiyorsa, sayfanıza JSON.stringify yöntemini tanımlayan json2.js komut dosyasını ekleyebilirsiniz.

Önemli not: Kesinlikle hiçbir zaman kodunuzdaki gibi dize birleştirme kullanarak JSON dizeleri oluşturun.

Bir JSON göndermek istemiyorum Alternatif eğer

standart bir application/x-www-form-urlencoded istek gönderebilir rica:

$.ajax({ //actually approve or reject the promotion 
    url: url, 
    type: "POST", 
    data: { 
     promotionId: data.PromotionId, 
     userId: data.UserId, 
     reasonText: data.ReasonText 
    }, 
    success: function (data) { 
     if (indicator == 'A') { 
      alert('Promotion approved successfully!'); 
     } 
     else { 
      alert('Promotion rejected successfully.'); 
     } 

     var homelink = '<%: Url.Action("Index","Home") %>'; 
     window.location.href = (homelink); 

     returndata = data; 
    }, 
    error: function (xhRequest, ErrorText, thrownError) { 
     alert("Failed to process promotion correctly, please try again"); 
     console.log('xhRequest: ' + xhRequest + "\n"); 
     console.log('ErrorText: ' + ErrorText + "\n"); 
     console.log('thrownError: ' + thrownError + "\n"); 
    } 
}); 

Bu aynı şekilde ve düzgün bir model bağlamak gerekir kontrolör eylemi çalışmalıdır.

Not: Başarının geri kalanında aşağıdaki satırı kullandığını fark ettim: returndata = data;. Bu, bir şekilde, senkronize olmayan AJAX isteğinin sonucunun başarılı bir şekilde geri çağrılma başarısı dışında tüketilmeye çalıştığına inanmamı sağlar. Bu returndata değişkeniyle ne yaptığınızı bilmiyorum ama yanlış olduğunu hissediyorum.

+0

Evet, bunun bir şekilde kırıldığını ve yukarıdaki kodun iki düz saat boyunca üzerinde çalıştıktan sonra olan ve gittikçe hayal kırıklığına uğramış olduğunu anladım. Bunu bir adım atıp çalıştığı zaman cevap olarak işaretleyeceğim. – Pseudonym

+0

Mükemmel çalıştı, yardımsever ve bilgilendirici cevabınız için teşekkürler. – Pseudonym

+0

Harika cevap ... – Mark