2012-03-13 4 views
0

컨트롤러 메서드 또는 사용자 정의 예외 필터에서 반환 된 상태 또는 오류 메시지를 포함하는 JSON 결과를 구문 분석하고 메시지를 표시하려고합니다.컨트롤러에서 반환 된 JSON 결과를 파싱하는 jQuery

 $.ajax({ 
     url: "/Account/LogOn", 
     type: "POST", 
     dataType: "json", 
     data: form.serialize(), 
     success: function (result) { 
      alert(result);  
     } 
    }); 

이 코드를 사용하면 특정 동작 결과 나 방법으로이를 수행 할 수 있다고 생각합니다. 페이지로 반환 된 모든 JSON 결과에 대해이 작업을 수행 할 수있는 방법이 있습니까?

답변

2

아니, 구조가 다른 것이 result 변수의 특성이 동일하지 않기 때문에 컨트롤러 액션에 의해 반환 가능한 모든 JSON이 작업을 수행 할 수있는 방법이 없습니다.

올바른 방법은 모든 예외를 가로 채고 잘 정의 된 JSON 구조로 랩핑하는 사용자 정의 오류 처리기를 사용하는 것입니다. 그런 다음 AJAX 요청의 오류 콜백을 사용하여이 사례를 처리 할 수 ​​있습니다.

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new AjaxErrorHandlerAttribute()); 
} 

와 클라이언트에서 당신은 또한 같은 페이지에있는 모든 AJAX 요청에 대한 글로벌 AJAX 오류 처리기 수 : :

$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { 
    var json = $.parseJSON(jqXHR.response); 
    alert(json.ErrorMessage); 
}); 
을 글로벌 액션 필터로 등록 할 수

public class AjaxErrorHandler : FilterAttribute, IExceptionFilter 
{ 
    public void OnException(ExceptionContext filterContext) 
    { 
     if (filterContext.HttpContext.Request.IsAjaxRequest()) 
     { 
      filterContext.Result = new JsonResult 
      { 
       Data = new 
       { 
        ErrorMessage = filterContext.Exception.Message 
       }, 
       JsonRequestBehavior = JsonRequestBehavior.AllowGet 
      }; 
      filterContext.ExceptionHandled = true; 
      filterContext.HttpContext.Response.Clear(); 
      filterContext.HttpContext.Response.StatusCode = 500; 
      filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 
     } 
    } 
} 

+0

예외를 던지려면 어떻게해야합니까? 나는 시도 [HttpPost] [AjaxErrorHandler] 공공 ActionResult 로그온 (LogOnModel 모델, 문자열 returnUrl) { // 일부 코드 경우 (blabla) 던져 새로운 예외 ("blaBla"); }하지만 작동하지 않았다. –

+0

Html.BeginForm 대신 Ajax.BeginForm을 시도했습니다. 예외는 AjaxErrorHandler를 통해 발생하지만 클라이언트의 전역 Ajax 오류 핸들러는 메시지를 표시하지 않습니다. –

0
$.ajax({ 
    url: "/Account/LogOn", 
    type: "POST", 
    dataType: "json", 
    data: form.serialize(), 
    success: function (result) { 
     alert(result);  
    } 
    error: function (req, status, error) { 
     //your logic 
    } 
}); 
관련 문제