Retrieve Session variables into ASP.NET MVC 4 (razor, view)

michaldck picture michaldck · Jun 9, 2013 · Viewed 96.1k times · Source

I wrote many websites with PHP. Now, I have to create website with ASP MVC 4 (c#) and I am stuck with Sessions.

I.E. the user should go to login page, enter his/her login and password. If they are correct, in controller, I set the session with UserId, like this:

Session["UserId"] = 10

This UserId value is used for showing PartialViews (login form or (after login) some application menus). How can I get this UserId inside Razor view ?

After this in View:

if (Session.UserId == 10) { @Html.Partial("LoggedMenu") }

i've got exception with StackOverflow. :/

Answer

balexandre picture balexandre · Jun 9, 2013

you're doing it wrong...

Session[<item name>] returns a string, you should compare with a string as well, or cast it, so, either (int)Session["UserId"] == 10 or Session["UserId"] = "10".

you also are invoking a property that does not exist Session.UserId will not exist as Session is like an NameValueCollection, you call it by request it's item name.

at the end, you should write

@if (Session["UserId"] == "10") { 
    Html.Partial("LoggedMenu"); 
}

You say your are learning, so I would like to point out 2 quick things:

  • You should take advantage of the ASP.NET MVC Course that is available for free in the home page http://asp.net/mvc (right side when you read "Essential Videos")
  • Create an MVC3 project and see how they do it as it comes ready out of the box with Membership