views:

1071

answers:

3

Let's say I want to store a language_id in the session. I tought I maybe could 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?

A: 

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
+1  A: 

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.

bzlm
+1  A: 

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