2011-11-08 66 views
5

獲得異常消息我有一個動作:ASP.NET MVC中的Ajax

[HttpPost] 
public ActionResult MyAction(MyModel model) 
{ 
    ... 
    if (model.MyCondition == true) 
     throw new Exception("MyMessage); 
    .... 
} 

我想坐上阿賈克斯消息 「MyMessage」:

onSuccess: function() { 
... 
}, 
onError: function (jqXHR, textStatus, errorThrown) { 
//I'd like get "MyMessage" here 
} 

一個想法如何做這個 ?當我用調試器檢查時,我沒有看到我的字符串。

回答

8

實現錯誤屬性是一個好方法。另外,我通常不會拋出異常,但根據錯誤返回status code。您可以通過XMLHttpRequest.responseText寫信給您迴應流和JS訪問:

if (model.MyCondition == true) 
{ 
    if (Request.IsAjaxRequest()) 
    { 
     Response.StatusCode = 406; // Or any other proper status code. 
     Response.Write("Custom error message"); 
     return null; 
    } 
} 

和JS:

... 
error: function (xhr, ajaxOptions, errorThrown) { 
    alert(xhr.responseText); 
} 
0

嘗試使用GET類型操作從Action中返回ContentResult。

[HttpGet] 
public ContentResult MyAction(String variablename) 
{ 
    ... 
    if (some_verification == true) 
     return Content("MyMessage); 
    .... 
} 

在您的視圖頁面,

$.ajax({ 
    url: 'your controller/action url', 
    type: 'get', 
    cache: false, 
    async: false, 
    data: { variablename: "value" }, 
    success: function (data) { 
     alert(data); 
    }, 
    error: function() { 
     alert('Error doing some work.'); 
    } 
}); 
+0

問題是從異常拋出的字符串中獲取控制器沒有辦法改變調用行動 –

+0

啊。謝謝。 – Muthu

0

我已經解決了這個實現自定義ErrorAttribute:

[NonAction] 
protected void OnException(ExceptionContext filterContext) 
{ 

    this.Session["ErrorException"] = filterContext.Exception; 

    if (filterContext.Exception.GetType() == typeof(MyException)) 
    { 
     // Mark exception as handled 
     filterContext.ExceptionHandled = true; 
     // ... logging, etc 
     if (Request.IsAjaxRequest()) 
     { 
      /* Put your JSON format of the result */ 
      filterContext.Result = Json(filterContext.Exception.Message); 
     } 
     else 
     { 
      // Redirect 
      filterContext.Result = this.RedirectToAction("TechnicalError", "Errors"); 
     } 
    } 
} 

,然後裝飾我用它的行動。

您也可以重寫控制器的OnException方法,但我認爲自定義屬性方式更加靈活。

0

一個可能性是要創造一個你重寫控制器的OnException(ExceptionContext filterContext)方法和轉換BaseController類JSON中的例外情況能夠輕鬆地從JavaScript客戶端處理它們。