2017-03-24 68 views
1

有一個類似的問題,但我仍然無法解決它在我的情況。Ajax請求返回200,但錯誤事件被觸發

這是我的控制器方法:

[HttpPost] 
    [ActionName("SaveProduct")] 
    public IHttpActionResult SaveProduct(Product product) 
    { 
     bool saved = db.Instance.SaveProduct(product); 
     if (saved) 
     { 
      IHttpActionResult response; 
      HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); 
      string url = "http://localhost:8080/products/success.aspx"; 
      responseMessage.Content = new StringContent(url, System.Text.Encoding.UTF8, "application/json"); 
      response = ResponseMessage(responseMessage); 
      return response; 
     } 
     return NotFound(); 
    } 

誤差會始終點火

$("#btnTest").on("click", function() { 
     var product = {}; 
     product.Code = $("#txtCode").val(); 
     product.Name = $("#txtName").val(); 
     var url = "http://localhost:8080/api/products/SaveProduct"; 
     $.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      data: JSON.stringify(product), 
      url: url, 
      success: function(response){ 
      alert("ok"); 
      }, 
      error: function(response, status, request){ 
      alert("error"); 
      } 
     }); 
    }); 
+0

錯誤處理程序有三個參數) – Andreas

+0

@Andreas,感謝您的評論。我現在添加了3個參數,但仍然無法解決我的問題。錯誤處理程序不應該被提出,而是成功的一個。 –

+0

爲什麼你返回Ajax調用的HttpResponseMessage?返回應該是'Ok();' – Win

回答

0

我知道了。希望可以幫助別人

我換成這個

 string url = "http://localhost:8080/products/success.aspx"; 
     responseMessage.Content = new StringContent(url, System.Text.Encoding.UTF8, "application/json"); 

對於這個

 responseMessage.Headers.Location = new Uri(url); 
     responseMessage.Content = new StringContent("{}"); 
相關問題