Dynamically load layout based on condition in MVC4

I have a _Layout.cshtml page which will render every time when a view is loaded. I have a session variable which stores the current user. While loading a view I need to check whether that session is out. If session out I need to render another view to prompt the user to login again.

I have written this code in the _Layout.cshtml

  @if( @Session["UserId"]!=null)
        {/* Header,RenderBoady(),footer etc of layout goes here */}
        else 
{/*call another view here*/}

I dont know what have to write on else part.

Upvotes: 2

Views: 4181

Answers (2)

Bhalchandra K
Bhalchandra K

Reputation: 2681

  1. Use asp.net mvc authorze filter attribute for user authentication,
  2. Enable forms authentication in web.config
  3. Use _ViewStart.cshtml and perform this check in that file. Based on status set the layout page for logged in user and logged out users

    @{
      if( @Session["UserId"]!=null)
       {
          Layout = "~/Views/Shared/_Layout.cshtml";
       }
       else
       {
         Layout = "~/Views/Shared/_LayoutPartial.cshtml";
       }
    }
    

Upvotes: 2

Dima
Dima

Reputation: 6741

Most likely, you need redirect user rather than vary layout. I suggest to use filters for this task and may think of 2 solutions.

First, utilize built-in [Authorize] attribute to reduce amount of custom logic.
Second, use custom AuthorizeFilter, which may looks like one below:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
  public override void OnAuthorization(AuthorizationContext filterContext)
  {
    Controller controller = filterContext.Controller as Controller;

    if (IsSessionExpired(filterContext))
    {
      filterContext.Result = new RedirectResult(<where to redirect>);
    }
  }

  private bool IsSessionExpired(AuthorizationContext filterContext)
  {
    <logic>
  }
}

Pick any you like and register as global filter or mark specific contollers/actions.

Upvotes: 2

Related Questions