Redirect a controller automatically from a view .cshtml

4

I have a mvc web application that requests as a homepage to verify your identification and if it is correct send to the main page, the action is correctly fulfilled using authentication Forms and redirects to this if you try to go directly via url to another address, but when you return to the login page via url when you are already identified, it returns to display the login forms. Try the following, but request the user's manual action via link.

 @if (Request.IsAuthenticated)
{
    @Html.ActionLink("Salir", "Index", "Home")       
}
  • Is it advisable to redirect from one view to another directly or is the use of a controller essential to avoid abnormalities?
asked by Miko 11.02.2016 в 19:11
source

3 answers

2

In principle I do not see what is the problem of entering the login page once authenticated, you might want to enter with another different user, although it is true that the correct thing would be to make a logoff

You could in the login view use server code with javascript, something like:

@if (Request.IsAuthenticated){
   <script> window.location.href='@Url.Action("Home", "Index")'; </script>
}

This way, when you render the login view, you will enter this script that will execute as soon as it loads, redirecting to the page you define.

    
answered by 11.02.2016 / 19:53
source
2

Leandro's answer can work for you, although I think it would be ideal to do it from the controller:

    public ActionResult LogIn()
    {
        if(Request.IsAuthenticated)
            return RedirectToAction("Index", "Home");
        return View();
    }
    
answered by 16.02.2016 в 19:47
1

Another option is to make the homepage behave differently depending on whether the user is authenticated or not.

  • If the unauthenticated user would display the form to enter the username and password
  • If is authenticated could show the user's name and two links, one to log out and one to go to the homepage

One way to implement it would be to have two different views for each case Login.cshtml and LoginAuthenticated.cshtml because each one has a different design

In the action of the controller you would have this code:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    if (Request.IsAuthenticated)
    {
        return View("LoginAutenticathed");
    }
    else
    {
        return View();
    }
}

Something important that we should keep in mind when we develop is that we have to respect the patterns.

In this case, the MVC pattern implies that the requests pass through by the controller, there are processed and made the appropriate operations and prepare the data (model) that you paint in the view.

Therefore the redirection must be done in the controller as Jorge Mauricio González commented and not in the view

    
answered by 16.02.2016 в 23:13