2

Let's say I want to store a variable called language_id in the session. I thought I might be able to do something like the following:

public class CountryController : Controller
{ 
    [WebMethod(EnableSession = true)]  
    [AcceptVerbs(HttpVerbs.Post)]  
    public ActionResultChangelangue(FormCollection form)
    {
        Session["current_language"] = form["languageid"];
        return View();    
    } 
}

But when I check the session it's always null. How come? Where can I find some information about handling session in ASP.NET MVC?

Benjamin Gale
  • 12,977
  • 6
  • 62
  • 100
Tom Maeckelberghe
  • 1,969
  • 3
  • 21
  • 24
  • Isn't [WebMethod] only for ASP.NET web services? – bzlm Mar 22 '09 at 17:52
  • Can you show us the code that access the variable from the session as you only show the code to set the value? Also bear in mind that in the beginning of your question you refer to a variable called `language_id` but your code for setting the session refers to a `languageid` variable (no underscore). – Benjamin Gale Sep 10 '12 at 15:20

3 Answers3

12

Not strictly related to the question itself, but more as a way of keeping controllers (reasonably) strongly typed and clean, I would also recommend a Session facade like class which wraps any session information in it, so that you read and write it in a nice way.

Example:

public static class SessionFacade
{
  public static string CurrentLanguage
  {
    get
    {
      //Simply returns, but you could check for a null
      //and initialise it with a default value accordingly...
      return HttpContext.Current.Session["current_language"].ToString();
    }
    set
    {
      HttpContext.Current.Session["current_language"] = value;
    }
  }
}

Usage:

public ActionResultChangelangue(FormCollection form)
{
  SessionFacade.CurrentLanguage = form["languageid"];
  return View();
} 
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
1

It should work, but is not a recommended strategy. Maybe session state is turned off in IIS or ASP.NET? See this answer and its comments.

Community
  • 1
  • 1
bzlm
  • 9,626
  • 6
  • 65
  • 92
0

You may have to enable session within the web.config as well. Also there is an article on session state and state value here:

http://www.davidhayden.com/blog/dave/archive/2008/02/06/ASPNETMVCFrameworkSessionStateStateValueWCSF.aspx

Hope this helps.

Richard
  • 21,728
  • 13
  • 62
  • 101