2012-03-18 91 views
1

我試圖做一個Ajax調用登錄使用輸入到jQuery UI對話框的憑據。asp.net mvc4 ajax登錄:RedirectToAction不工作

ajax調用正確記錄用戶併成功返回RedirectToAction(「Index」,「Home」)調用。但是,用戶不會立即看到他們已經登錄。我必須刷新_LoginPartial狀態欄的頁面才能從註冊/登錄切換到用戶名/註銷。

我會認爲RedirectToAction(「Index」,「Home」)調用會刷新頁面。 我試圖將其切換到RedirectToAction(「索引」,「其他一些頁面」),雖然它通過指定的操作方法運行,但不會重定向到該頁面。

這裏是Ajax調用:

  $.ajax({ 
          url: "/Account/Login", 
          type: "POST", 
          data: JSON.stringify($('#loginForm').serializeObject()), 
          dataType: 'json', 
          contentType: "application/json; charset=utf-8", 
          complete: function() { 
           $('.dialogContainer').dialog("close"); 
          } 
         }); 

控制器:

[HttpPost] 
    public ActionResult Login(LoginModel model, string returnUrl) 
    { 

     if (ModelState.IsValid) 
     { 
      if (Membership.ValidateUser(model.UserName, model.Password)) 
      { 
       FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 
       if (Url.IsLocalUrl(returnUrl)) 
       { 
        return Redirect(returnUrl); 
       } 
       else 
       { 
        return RedirectToAction("Index", "Home"); 
       } 
      } 
      else 
      { 
       ModelState.AddModelError("", "The user name or password provided is incorrect."); 
      } 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 

回答

1

RedirectToAction不會做一個Ajax調用時工作。出於同樣的原因,ajax調用不會導致頁面刷新,您的RedirecToAction也不會導致頁面重定向。您正在重定向Ajax請求,而不是頁面。

你將不得不返回某種成功的指標給你的ajax調用,並讓你的ajax調用重定向頁面。