Teodoris
Teodoris

Reputation: 109

How to redirect from one view to another view in MVC3?

Hello everyone I would like to ask how to redirect from one view to another. Here is my view

@model IEnumerable<test.Models.contents>
@using test   

@if(Request.IsAuthenticated) {
    <text>Welcome<strong>@User.Identity.Name</strong>
    </text>
}
else
{

     ???
}

Upvotes: 1

Views: 2540

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Don't do any redirects inside the view. That's not its responsibility. The responsibility of a view is to display data that is passed to it from the controller action under the form of a view model.

Do this redirect inside the controller action that is rendering this view. For example you could decorate it with the [Authorize] attribute. This way if the user is not authorized he will be redirected to the loginUrl you specified in your web.config:

[Authorize]
public ActionResult SomeAction()
{
    return View();
}

and if you wanted to redirect to some particular view you could simply write a custom Authorize attribute and override the HandleUnauthorizedRequest method to specify the controller and action you wish to redirect to in case of user not being authenticated:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var values = new RouteValueDictionary(new
        {
            controller = "SomeController",
            action = "NotAuthorized"
        });
        filterContext.Result = new RedirectToRouteResult(values);
    }
}

and then decorate your action with it:

[MyAuthorize]
public ActionResult SomeAction()
{
    return View();
}

Now inside the corresponding view you don't need to perform any tests. It is guaranteed that if you got as far as rendering this view the user is authenticated and you could welcome him directly:

@model IEnumerable<test.Models.contents>
@using test   

Welcome <strong>@User.Identity.Name</strong>

Upvotes: 6

Related Questions