2011-11-08 14 views
5
で例外メッセージ

私がアクションを持っているを取得しますこれを行う ?デバッガでチェックすると、文字列が表示されません。ASP.NET MVCは、Ajax

答えて

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タイプアクションでアクションから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

ah right。ありがとう。 – 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クラスを作成することができJavaScriptクライアントからJSONを簡単に処理できるというJSONの例外

関連する問題