2015-10-05 37 views
0

我想將ASP.NET MVC控制器拋出的異常消息傳遞給JQuery Ajax函數。但是信息沒有正確顯示。可能是它傳遞給成功塊,因此顯示時錯誤消息的顏色不正確。Controller中的catch塊引發的消息無法正確顯示

在控制器: -

[HttpPost] 
public string ABC() 
     { 
      try 
      { 
       //some codes here 
       return message; 
      } 
      catch (Exception ex) 
      { 
       return "An error has occurred."; 

      } 
     } 

在阿賈克斯功能: -

success: function (data1) { 
       var message = data1; 
       HideMasterProcessing(); 
       ShowNotificationMessage(message, "notifyMessage", "notify-info", false); 
      }, 


    error: function (data2) { 
        var message = data2; 
        HideMasterProcessing(); 
        ShowNotificationMessage(message, "notifyMessage","notify-errror", false); 
} 

我想顯示在 「通知錯誤」 DIV異常消息。但它正在「notify-info」div中顯示。

+0

你只是'返回',所以方法退出成功 –

+0

如果你返回字符串「發生錯誤」,那麼這不是一個HTTP錯誤。這是一個有效的迴應! – Liam

+0

異常消息是否傳遞給ajax中的錯誤塊?我到現在爲止的想法是,從嘗試塊傳遞到成功函數的消息以及從異常消息傳遞到錯誤塊的消息。這不正確嗎? – Lucky

回答

0

更好地解釋什麼是已經由科德羅伊波評論:

當你在catch塊中返回一個錯誤信息,該AJAX功能認爲它是成功的,這意味着它永遠不會停靠於AJAX「錯誤」塊。

你可以讓異常拋出和處理它在AJAX「錯誤」塊

或者保持這種方式,並返回一個撰寫的對象,這樣的事情:

[HttpPost] 
public string ABC() 
     { 
      try 
      { 
       //some codes here 
       return new {Message = message, Error = null}; 
      } 
      catch (Exception ex) 
      { 
       return new {Message = null, Error = "An error has occurred."};  
      } 
     } 

在阿賈克斯功能:

success: function (data1) { 
        HideMasterProcessing(); 
        if(data1.Error == null) 
        { 
         var message = data1.Message;      
         ShowNotificationMessage(message, "notifyMessage", "notify-info", false); 
        } 
        else 
        { 
         var message = data1.Error; 
         ShowNotificationMessage(message, "notifyMessage","notify-errror", false); 
        } 
       }, 


     error: function (data2) { 
         var message = data2; 
         HideMasterProcessing(); 
         ShowNotificationMessage(message, "notifyMessage","notify-errror", false); 
    } 

讓我知道,如果事實證明確定!

+0

由於返回類型是字符串,因此顯示錯誤。無論如何謝謝你的答案。 – Lucky

3

您沒有從控制器返回錯誤狀態,因此結果始終視爲成功。而不是隻返回一個字符串,使用ActionResult作爲一個包裝,以便您可以指定狀態代碼:

return new HttpStatusCodeResult(500, "An error occurred."); 
+0

這可以工作,但我不得不返回字符串,所以不能使用此方法。 – Lucky

0

這爲我工作:

[HttpPost] 

    public string ABC() 
      { 
       try 
       { 
        //some codes here 
        return message; 
       } 
       catch (Exception ex) 
       { 

       var message = "An error has occurred."; 
       return message; 

       } 
      } 

在阿賈克斯:

success: function (data1) { 
       if (data1 === "An error has occurred.") 
       { 
        HideMasterProcessing(); 
        ShowNotificationMessage("An error has occurred. Please contact administrator.", "notifyMessage", "notify-error", false); 
       } 
       else 
       { 
        HideMasterProcessing(); 
        var message = data1; 
        ShowNotificationMessage(message, "notifyMessage", "notify-info", false); 
       } 

我只是比較了從控制器傳遞的字符串與輸入成功塊的數據,然後將其顯示在所需的div中。