2013-01-11 4 views
5

私のAJAX呼び出しは、この継続的にMVCコントローラにjqueryのAjaxのポストに400(不正な要求)を受信

$.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"); 
       } 
      }); 

のように見え、私のMVCコントローラは次のようになります。私は、構文を考えていた

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

これらの両方で正しいですが、私がAjaxコールを行うたびに私は400応答を得ます。私が間違っていることは何ですか?

答えて

10

完全に壊れていて無効なJSON文字列をサーバーに送信しています。コントローラーのアクションがそれを拒否するのは正常です。それに加えて、contentTypeパラメータに、JSONリクエストを送信することを指定するコメントを書きました。

だからここに要求を行うには正しい方法です:私は、サーバーに送信されるJSONが正しくあることを保証するために、ネイティブの内蔵にされた近代的なブラウザJSON.stringify方法を使用していますか

$.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"); 
    } 
}); 

お知らせとすべての値が適切にエンコードされます。石器時代のブラウザをサポートする必要がある場合は、メソッドを定義するjson2.jsスクリプトをページに含めることができます。

重要なお知らせ:絶対に決してあなたのコードのように文字列連結を使用してJSON文字列を構築してください。また

あなたが標準application/x-www-form-urlencodedリクエスト送ることができJSONリクエスト送信したくない場合は:

$.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"); 
    } 
}); 

これは、同じように動作するはずですし、コントローラのアクションが正しくモデルをバインドすることができるはずですが。

備考:成功コールバックで次の行を使用したことに気付きました。returndata = data;これは、あなたが何とか非成功のAJAXリクエストを成功コールバックの外で消費することを試みていると信じています。これは不可能です。このreturndata変数で何をしているのか分かりませんが、間違っていると感じています。

+0

私はそれが何とか壊れていると思っていました。上記のコードは、2時間連続して作業していて、ますます不満を抱いた後に起こるものです。私はこれを行って、それが動作するときに答えとしてマークします。 – Pseudonym

+0

あなたの役に立つ有益な答えをいただきありがとうございます。 – Pseudonym

+0

すばらしい答え... – Mark

関連する問題