Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a Session object from Razor _Layout.cshml

Building an MVC 3 app with Razor and I have some information persisted in the Session scope that will be used in the _Layout file.

I have no clue as to what is the best way to implement this. Some of this information is used to determine what is rendered in the header.

I have a CurrentUser object stored in Session scope

like image 508
JBeckton Avatar asked Dec 07 '10 20:12

JBeckton


People also ask

What is _layout Cshtml?

So, the _layout. cshtml would be a layout view of all the views included in Views and its subfolders. Setting Layout View in _ViewStart.cshtml. The _ViewStart. cshtml can also be created in the sub-folders of the View folder to set the default layout page for all the views included in that particular subfolder.

What is the purpose of the _layout Cshtml file in the pages shared folder?

Layout pages are typically named _Layout. cshtml, the leading underscore preventing them from being browsed directly. Standard practice is to specify the layout page in a _ViewStart. cshtml file, which affects all content pages in the folder in which it is placed, and all subfolders.


2 Answers

You could just access the HttpContext in the layout file

@HttpContext.Current.Session["Whatever"].ToString() 

or, if you want access to the user object you could just create an object in the page and assign it

@{ CurrentUser user = (CurrentUser)HttpContext.Current.Session["CurrentUser"]; } 

Then later in your code...

@user.Name 
like image 156
Buildstarted Avatar answered Nov 03 '22 09:11

Buildstarted


An easier way to do it is using Session property directly from the view (HttpContext.Current. prefix should not be necessary at all):

@(CurrentUser)Session["CurrentUser"] 
like image 39
Emilio González Montaña Avatar answered Nov 03 '22 10:11

Emilio González Montaña