Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. :/

like image 301
michaldck Avatar asked Jun 08 '13 22:06

michaldck


People also ask

How can use session value in MVC view?

The Session value will be displayed using Razor Syntax in ASP.Net MVC. In the below example, a string value is set in the Session object in Controller and it is then displayed in View using Razor Syntax.

Can you use MVC with Razor pages?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.

Can we use session state in MVC?

By default, Asp.Net MVC support session state. Session is used to store data values across requests. Whether you store some data values with in the session or not Asp.Net MVC must manage the session state for all the controllers in your application that is time consuming.


2 Answers

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
like image 158
balexandre Avatar answered Sep 23 '22 19:09

balexandre


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

Apart from that: for identity management better use the out of the box membership system

like image 39
Mathias F Avatar answered Sep 22 '22 19:09

Mathias F