2016-07-28 36 views
0

我試圖在成功登錄後重定向到主頁。目前,我正在使用ASP.NET MVC 5,AngularJS,EntityFramework 6,引導程序和存儲庫模式。下面是我的LoginController代碼:爲AngularJS控制器從AngularJS控制器調用Asp.Net MVC 5查看

public JsonResult UserLogin(STUDENTMANAGEMENTUSER data) 
    { 
     var user = repository.UserLogin(data); 
     return new JsonResult { Data = user, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; 
    } 

代碼:

app.controller("mvcLoginCtrl", function ($scope, loginAJService) { 
$scope.IsLoggedIn = false; 
$scope.Message = ''; 
$scope.Submitted = false; 
$scope.IsFormValid = false; 

$scope.LoginData = { 
    USERNAME: '', 
    USERPASSWORD: '' 
}; 

//Check is Form Valid or Not // Here f1 is our form Name 
$scope.$watch('f1.$valid', function (newVal) { 
    $scope.IsFormValid = newVal; 
}); 

$scope.Login = function() { 
    $scope.Submitted = true; 
    if ($scope.IsFormValid) { 
     loginAJService.GetUser($scope.LoginData).then(function (d) { 
      if (d.data.USERNAME != null) { 
       $scope.IsLoggedIn = true; 
       $scope.Message = "Successfully login done. Welcome " + d.data.FULLNAME; 
      } 
      else { 
       alert('Invalid Credential!'); 
      } 
     }); 
    } 
};}); 

和代碼爲我AngularJS服務:

app.service("loginAJService", function ($http) { 

this.GetUser = function (d) { 
    var response = $http({ 
     method: "post", 
     url: "Login/UserLogin", 
     data: JSON.stringify(d), 
     dataType: "json" 
    }); 
    return response; 
};}); 

我想重定向到學生/索引。成功登錄後的cshtml。我怎樣才能做到這一點?

回答

0

您是否嘗試過:

return Json 
(
    new { 
      Data = user, 
      JsonRequestBehavior = JsonRequestBehavior.AllowGet, 
      redirectUrl = @Url.Action("UserLogin", "LoginController") 
     } 
); 

然後在角度在$ http.post等待成功回調:

success: function(data) { 
    window.location.href = data.redirectUrl; 
} 
1

你不直接訪問.cshtml視圖。您可以通過操作方法訪問它。因此,創建一個操作方法返回這個觀點(如果尚不存在)

public ActionResult StudentIndex() 
{ 
    // you may pass a view model to the view as needed 
    return View("~/Views/Student/Index.cshtml"); 
} 

現在,在您登錄成功,只要將這種操作方法。

if (d.data.USERNAME != null) { 
     $scope.IsLoggedIn = true; 
     $scope.Message = "Successfully login done. Welcome " + d.data.FULLNAME; 
     window.location.href='/YourControllerName/StudentIndex'; 
} 

既然你正在做一個重定向(一個完全新的HTTP GET請求StudentIndex,有在設定範圍內的屬性值是沒有意義的。

+0

感謝您的回覆,它的工作原理。另一件事我想要知道,我必須通過'$ scope.Message =「成功登錄完成。歡迎使用」+ d.data.FULLNAME;'這個變量到/Student/Index.cshtml視圖。我該怎麼做? –

+0

你應該遵循PRG所以在學生/索引中查詢你的用戶信息並顯示你想要做的任何消息 – Shyju

相關問題