2010-11-18 15 views
5

コントローラ:製品と処置:保存して、JsonResultを返します。トラップされた例外が発生した場合、私はそのエラーをクライアント(つまり:jQuery)にカスタムエラーメッセージで通知したいと思います。サーバーとクライアントの両方でどうすればいいですか?このシナリオで関数ポインタエラーを利用できますか?ユーザーが作ったとき、たとえば、IISがダウンしていた。ここでASP.NET MVC:AJAXリクエストがカスタムエラーメッセージで失敗したことをjQueryに通知します。

は、クライアントコードは要求があなたのコントローラのアクションが正常に完了しなかったという意味(失敗したときに参照error関数が呼び出され

$.ajax({ 
       url: '/Products/Save', 
       type: 'POST', 
       dataType: 'json', 
       data: ProductJson, 
       contentType: 'application/json; charset=utf-8', 
       error: function() 
       { 
        //Display some custom error message that was generated from the server 
       }, 
       success: function (data) { 
        // Product was saved! Yay 

       } 
      }); 

答えて

5

ですリクエスト)。 http://api.jquery.com/jQuery.ajax/を参照してください。

お使いのコントローラのアクションが正常に接触させ、あなたはクライアントをできるようにしたい場合は、何かが間違ったあなたのコントローラのアクション内で起こった、あなたはクライアント側のJSが理解ErrorまたはErrorCodeプロパティが含まれているJsonResultを返す必要があることを知っています。

たとえば、あなたのコントローラのアクションは次のようになります:

public ActionResult Save() 
{ 
    ActionResult result; 
    try 
    { 
     // An error occurs 
    } 
    catch(Exception) 
    { 
     result = new JsonResult() 
     { 
     // Probably include a more detailed error message. 
     Data = new { Error = true, ErrorMessage = "Product could not be saved." } 
     }; 
    } 
    return result; 
} 

をそして、あなたはそのエラーを解析するために、次のJavaScriptを記述します。

$.ajax({ 
    url: '/Products/Save', 
    'POST', 
    'json', 
    ProductJson, 
    'application/json; charset=utf-8', 
    error: function() 
    { 
     //Display some custom error message that was generated from the server 
    }, 
    success: function (data) { 
     if (data.Error) { 
     window.alert(data.ErrorMessage); 
     } 
     else { 
     // Product was saved! Yay 
     } 
    } 
}); 

お役に立てば幸いです。

0

私は、エラーをキャッチし、それがバックプレーンテキストとして送信されることを確認だけでなく、jQueryのを知っているので、問題と誤差関数が実行されますがありました(500にエラーコードを設定するclientError属性を使用しました
/// <summary>Catches an Exception and returns just the message as plain text - to avoid full Html 
/// messages on the client side.</summary> 
public class ClientErrorAttribute : FilterAttribute, IExceptionFilter 
{ 
    public void OnException(ExceptionContext filterContext) 
    { 
     var response = filterContext.RequestContext.HttpContext.Response; 
     response.Write(filterContext.Exception.Message); 
     response.ContentType = MediaTypeNames.Text.Plain; 
     response.StatusCode = (int)HttpStatusCode.InternalServerError; 
     response.StatusDescription = filterContext.Exception.Message; 
     filterContext.ExceptionHandled = true; 
    } 
} 
関連する問題