Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

Session variable fine in one action, null in next

I have a simple application. When a user logs in it creates a session variable and redirects them to another controller that pull up some info from the database. I need to store this to a session variable then return it to the view. The initial part is fine, it returns it and I see the information. However, when I try to create a search query it returns that the session is null even though I never clear it.

public ActionResult ShowCourses()
{
    if (Session["Username"] != null)
    {
        string Username = Session["Username"].ToString();

        using (DefaultConnection db = new DefaultConnection())
        {
            var model = from c in db.Courses
                        where c.Username == Username
                        select c;

            Session["Courses"] = model.ToList();
            var Courses = Session["Courses"];
            return View(Courses);
        }
    }
    else
    {
        return RedirectToAction("Login", "Users");
    }
}

But when I try to run a search query to loop through the session, it brings back that Courses is null. The problem is that coursesQuery returns null and I'm not sure why.

public ActionResult SearchCourses(string query)
{
    if (Session["Username"] != null)
    {
        var coursesQuery = Session["Courses"] as IEnumerable<Course>;

        if (coursesQuery != null)
        {
            // Do Something
        }
    }
}

Upvotes: 0

Views: 91

Answers (1)

Shyju
Shyju

Reputation: 218702

You did a .ToList() on the course colleciton before setting to Session.

Try this. Use List<Course> when you read it back.

if (Session["Courses"] != null)
{
  var coursesQuery = (List<Course>) Session["Courses"];
}

Upvotes: 1

Related Questions