I am trying to redirect to Home page after successful login. Currently, I am using ASP.NET MVC 5, AngularJS, EntityFramework 6, bootstrap and repository pattern. Below is the code for my LoginController:
public JsonResult UserLogin(STUDENTMANAGEMENTUSER data)
{
var user = repository.UserLogin(data);
return new JsonResult { Data = user, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
code for AngularJS controller:
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!');
}
});
}
};});
and code for my AngularJS service:
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;
};});
I want to redirect to Student/Index.cshtml after successful login. How can i achieve this?
Have you tried:
return Json
(
new {
Data = user,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
redirectUrl = @Url.Action("UserLogin", "LoginController")
}
);
And then in angular in $http.post wait for a success callback:
success: function(data) {
window.location.href = data.redirectUrl;
}
You do not access a .cshtml view directly. You access it via an action method. So create an action method to return this view ( if not already exist)
public ActionResult StudentIndex()
{
// you may pass a view model to the view as needed
return View("~/Views/Student/Index.cshtml");
}
Now in your login success, simply redirect to this action method.
if (d.data.USERNAME != null) {
$scope.IsLoggedIn = true;
$scope.Message = "Successfully login done. Welcome " + d.data.FULLNAME;
window.location.href='/YourControllerName/StudentIndex';
}
Since you are doing a redirect ( a totally new Http GET request to the StudentIndex, there is no point in setting the scope property values.