2011-03-02 2 views
0

비밀번호 분실 양식에서 jquery ajax 게시물이 여러 번 (각 제출 후 한 번 더) 해고됩니다. 따라서 사용자가 잘못된 이메일을 세 번 입력 한 다음 올바른 이메일을 입력하면 사용자는 비밀번호로 변경된 이메일을 4 회 가져옵니다. 오류가 발생할 때마다 이벤트가 쌓인 것처럼 보이며 모든 이벤트가 다음 제출시에 해고됩니다. 여기 내 모든 관련 코드가 있습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

JS

RetrievePassword = function() { 
     var $popup = $("#fancybox-outer"); 
     var form = $popup.find("form"); 
     form.submit(function (e) { 
      var data = form.serialize(); 
      var url = form.attr('action'); 
      $.ajax({ 
       type: "POST", 
       url: url, 
       data: data, 
       dataType: "json", 
       success: function (response) { 
        ShowMessageBar(response.Message); 
        $.fancybox.close() 
       }, 
       error: function (xhr, status, error) { 
        ShowMessageBar(xhr.statusText); 
       } 
      }); 
      return false; 
     });  
    }; 

MVC CONTROLLER/ACTION

[HandlerErrorWithAjaxFilter, HttpPost] 
     public ActionResult RetrievePassword(string email) 
     { 
      User user = _userRepository.GetByEmail(email); 

      if (user == null) 
       throw new ClientException("The email you entered does not exist in our system. Please enter the email address you used to sign up."); 

      string randomString = SecurityHelper.GenerateRandomString(); 
      user.Password = SecurityHelper.GetMD5Bytes(randomString); 
      _userRepository.Save(); 

      EmailHelper.SendPasswordByEmail(randomString); 

      if (Request.IsAjaxRequest()) 
       return Json(new JsonAuth { Success = true, Message = "Your password was reset successfully. We've emailed you your new password.", ReturnUrl = "/Home/" }); 
      else 
       return View();   
     } 

HandlerErrorWithAjaxFilter

public class HandleErrorWithAjaxFilter : HandleErrorAttribute 
    { 
     public bool ShowStackTraceIfNotDebug { get; set; } 
     public string ErrorMessage { get; set; } 

     public override void OnException(ExceptionContext filterContext) 
     { 
      if (filterContext.HttpContext.Request.IsAjaxRequest()) 
      { 
       var content = ShowStackTraceIfNotDebug || filterContext.HttpContext.IsDebuggingEnabled ? filterContext.Exception.StackTrace : string.Empty; 
       filterContext.Result = new ContentResult 
       { 
        ContentType = "text/plain", 
        Content = content 
       }; 

       string message = string.Empty; 
       if (!filterContext.Controller.ViewData.ModelState.IsValid) 
        message = GetModeStateErrorMessage(filterContext); 
       else if (filterContext.Exception is ClientException) 
        message = filterContext.Exception.Message.Replace("\r", " ").Replace("\n", " "); 
       else if (!string.IsNullOrEmpty(ErrorMessage)) 
        message = ErrorMessage; 
       else 
        message = "An error occured while attemting to perform the last action. Sorry for the inconvenience."; 

       filterContext.HttpContext.Response.Status = "500 " + message; 
       filterContext.ExceptionHandled = true; 
       filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 
      } 
      else 
      { 
       base.OnException(filterContext); 
      } 
     } 

     private string GetModeStateErrorMessage(ExceptionContext filterContext) 
     { 
      string errorMessage = string.Empty; 
      foreach (var key in filterContext.Controller.ViewData.ModelState.Keys) 
      { 
       var error = filterContext.Controller.ViewData.ModelState[key].Errors.FirstOrDefault(); 
       if (error != null) 
       { 
        if (string.IsNullOrEmpty(errorMessage)) 
         errorMessage = error.ErrorMessage; 
        else 
         errorMessage = string.Format("{0}, {1}", errorMessage, error.ErrorMessage); 
       } 
      } 

      return errorMessage; 
     } 

    } 

여기서 더 JS이다. 내 라이트 박스로 fancybox 플러그인을 사용하고 있습니다. 비밀번호 찾기 링크는 로그인 라이트 박스에 있습니다.

$(document).ready(function() { 

    $(".login").fancybox({ 
     'hideOnContentClick': false, 
     'titleShow': false, 
     'onComplete': function() {  

      $("#signup").fancybox({ 
       'hideOnContentClick': false, 
       'titleShow':false, 
       'onComplete': function() { 

       } 
      }); 

      $("#retrievepassword").fancybox({ 
       'hideOnContentClick': false, 
       'titleShow': false, 
       'onComplete': function() { 

       } 
      }); 
     } 
    }); 

}); 
+0

더 많은 자바 스크립트 코드를 게시 할 수 있습니까? 가장 가능성있는 일은 실수로 제출할 때마다 제출 코드를 다시 바인딩하는 것입니다. 이것은 나에게 몇 번 일어났습니다. – jfar

+0

고마워, 나는 더 많은 js를 추가했다 ... – Prabhu

답변

0

내가 jQuery를 전문가가 아니지만, 그 때마다 fancybox이 불을 onComplete를 나에게 나타납니다, 당신은 #retrievepassword하는 (다른) 이벤트 핸들러를 추가하고 #signup ... 나는 나머지를 누락 페이지의 html로 로그인 대화 상자의 내용이로드 될 때 알 수 없지만 다음 내용이 더 잘 작동 할 수 있습니다.

$(document).ready(function() { 

    $(".login").fancybox({ 
     'hideOnContentClick': false, 
     'titleShow': false, 
     'onComplete': function() {  

     } 
    }); 

    $("#signup").fancybox({ 
     'hideOnContentClick': false, 
     'titleShow':false, 
     'onComplete': function() { 

     } 
    }); 

    $("#retrievepassword").fancybox({ 
     'hideOnContentClick': false, 
     'titleShow': false, 
     'onComplete': function() { 

     } 
    }); 
}); 
+0

그건 그렇고 - 나는 _ 당신의 HandleErrorWithAjaxFilter를 좋아한다. 나는 언젠가 그걸 빌려야 할 것 같다 ... –

+0

팁 주셔서 감사합니다. Btw, 여기에서 HandleErrorWithAjaxFilter를 얻었습니다. http://erikzaadi.com/blog/2009/12/22/AspdotNETMVCExceptionHandlingWithJQuery.xhtml 모델 스테이트 에러를 태그하는 것이 좋을지 모르겠습니다. 모델 상태 오류를 응용 프로그램 예외로 throw 할 수 있습니다. 나는 이것에 대해 여기에 게시했다 : http://stackoverflow.com/questions/5171684/whats-the-recommended-way-to-report-model-state-and-application-errors-to-client 의견은 어떻습니까? – Prabhu

+0

잘 모르겠습니다. 테스트 해봐야 할 것 같습니다. 자바가 비활성화 된 경우 하위 호환성을 위해 좋아 보인다 ... –

관련 문제