I am kind of new to the ASP.NET MVC framework and I have a small question. I have a view user control that I want to use to display the login status of a user. I tried the following code but it doesn't seem to be working:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LoginStatus.ascx.cs" Inherits="PacificaWeb.Views.Shared.LoginStatus" %>
<%@ Import Namespace="System.Web.Mvc" %>
<% if( HttpContext.Current.Session[ "login" ] != null ) { %>
You are logged in as <%= HttpContext.Current.Session[ "username" ] %> |
<%= Html.ActionLink( "Logout", "Logout", new { Controller = "Login" } ) %>
<% } else { %>
You are not logged in |
<%= Html.ActionLink( "Login", "Login", new { Controller = "Login" } ) %>
<% } %>
I know that the session stuff is working because the controllers can see the session data. What's the right way to have a ViewUserControl get access to the current session? Thanks.
nomadjourney
Member
6 Points
6 Posts
Session data access from ViewUserControl
May 28, 2008 03:57 PM|LINK
Hello all,
I am kind of new to the ASP.NET MVC framework and I have a small question. I have a view user control that I want to use to display the login status of a user. I tried the following code but it doesn't seem to be working:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LoginStatus.ascx.cs" Inherits="PacificaWeb.Views.Shared.LoginStatus" %> <%@ Import Namespace="System.Web.Mvc" %> <% if( HttpContext.Current.Session[ "login" ] != null ) { %> You are logged in as <%= HttpContext.Current.Session[ "username" ] %> | <%= Html.ActionLink( "Logout", "Logout", new { Controller = "Login" } ) %> <% } else { %> You are not logged in | <%= Html.ActionLink( "Login", "Login", new { Controller = "Login" } ) %> <% } %>I know that the session stuff is working because the controllers can see the session data. What's the right way to have a ViewUserControl get access to the current session? Thanks.
-- Nizam
rjcox
Contributor
7064 Points
1444 Posts
Re: Session data access from ViewUserControl
May 28, 2008 04:21 PM|LINK
First, I would avoid HttpContext.Current, instead use the Session property inherited from UserControl (via ViewUserControl).
Second, better to use the User property (of ViewUserControl.ViewContent.HttpContext) to check if the user is logged on:
<% if (String.IsNullOrEmpty(ViewContext.HttpContext.User.Identity.Name)) { Response.Write(Html.ActionLink("Login", "login", "User")); } else { Response.Write(Html.ActionLink("Logoff", "logoff", "User")); } %>(From my own test app... now corrected to not use HttpContext.Current.)
BTW, avoid HttpContext.Current because it is much harder to mock for your unit tests than the ViewContext).
nomadjourney
Member
6 Points
6 Posts
Re: Session data access from ViewUserControl
May 29, 2008 02:01 PM|LINK
Thanks for the tip. It worked perfectly.