Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - HtmlHelper and Session data

I want to create a helper that searches through session data, Preferably something like this:

public static bool CheckForModerator(this HtmlHelper htmlHelper)
{
    return Session["isAdmin"];
}

But i cannot access Session[] data. I tried looking through htmlHelper, but i cannot find Session there either. What do i need to do in order to access Session data?

like image 857
ojek Avatar asked Jan 29 '13 17:01

ojek


People also ask

What is session data in MVC?

Session is derived from the HttpSessionStateBase class and is used for persisting data i.e. State Management across requests in ASP.Net MVC Razor. What is Session. 1. Session saves data similar to a Dictionary object i.e. Keys and Values where Keys are String while Values will be objects.

What is MVC HtmlHelper?

HTML Helpers are managed within View to execute HTML content. We can use HTML Helpers to implement a method that returns a string. This tutorial discusses how you can define or create custom HTML Helpers that you can use within your MVC views.

How can I store data temporarily in MVC like session?

TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type and instance property of the Controller base class. TempData is able to keep data for the duration of a HTP request, in other words it can keep live data between two consecutive HTTP requests.


2 Answers

using System.Web;

and then

HttpContext context = HttpContext.Current;
return context.Session["isAdmin"];
like image 78
Forty-Two Avatar answered Nov 14 '22 23:11

Forty-Two


Prefer (bool)htmlHelper.ViewContext.HttpContext.Session["IsAdmin"]

like image 27
David Avatar answered Nov 15 '22 01:11

David