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?

2
  • Isn't [WebMethod] only for ASP.NET web services? Commented Mar 22, 2009 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). Commented Sep 10, 2012 at 15:20

3 Answers 3

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();
} 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.