2010-09-29 154 views
4

我遇到了一些問題,通過.ajax錯誤從控制器捕獲錯誤消息。該腳本由jQuery UI對話框彈出。任何幫助,將不勝感激。asp.net mvc .ajax錯誤捕獲

下面是從我的控制器

  Response.StatusCode = (int)HttpStatusCode.BadRequest; 
      return Content("There was an error in your request.", MediaTypeNames.Text.Plain); 

的代碼段,這裏的jQuery腳本:

function submitFormWithAjax(form) { 
    form = $(form); 
    $.ajax({ 
     url: form.attr('action'), 
     data: form.serialize(), 
     type: (form.attr('method')), 
     dataType: 'text', 
     error: function(data) { 
      $('#result').html(data); 
     }, 
     success: function(data) { 
      $('#result').html(data); 
      setTimeout("reloadPage()", 500); 
     } 
    }); 
    return false; 
} 

error: function(data)不讀書返回的錯誤信息。有什麼建議麼?

回答

1

錯誤回調的簽名是function(xmlHttpRequest, textStatus, exceptionThrown)

也許您正在查看錯誤的參數?

+0

謝謝,我改變了代碼錯誤:功能(xmlHttpRequest,textStatus,exceptionThrown),我可以訪問xmlHttepRequest。但是,如何在控制器中附加我的錯誤消息?我想返回內容(「您的請求有錯誤」,MediaTypeNames.Text.Plain);是不正確的。 – Dean 2010-10-01 13:28:55

+0

我對ASP.NET MVC並不熟悉,但我的猜測是你必須返回一個View。這就是我迄今爲止所能提供的。 – Thomas 2010-10-01 13:43:59

1

試試這個:

function submitFormWithAjax(form) { 
    form = $(form); 
    $.ajax({ 
     url: form.attr('action'), 
     data: form.serialize(), 
     type: (form.attr('method')), 
     dataType: 'text', 
     error: function(data) { 
      $('#result').html(data); 
     }, 
     success: function(xmlHttpRequest, textStatus, exceptionThrown) { 
      $('#result').html(xmlHttpRequest.statusText); 
      setTimeout("reloadPage()", 500); 
     } 
    }); 
    return false; 
} 
1

它必須是一些關於返回一個錯誤請求(錯誤400)錯誤回調似乎被調用時,返回的代碼是Conflic(錯誤409)。

3

感謝大家的幫助。我想通了一些嘗試後,所有我需要做的就是這個jQuery的

error: function(xhr, textStatus, exceptionThrown) { 
     $('#result').html(xhr.responseText); 
    }, 

,這在控制器

  Response.StatusCode = (int)HttpStatusCode.BadRequest; 
      return Content("There was an error in your request."); 

乾杯

+0

問題在於如果在處理過程中出現異常,完整的錯誤頁面html將被轉儲到您的結果div中。 – UpTheCreek 2010-11-04 11:48:28