Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Managing a session's variable in a model class with asp.net mvc

I have an asp.net mvc4 application in which i have this snippet:

   public bool Logout() {
            try {
                session["user"] = null;
                return true;
            }
            catch {
                return false;
            }
                          }

when i put this code in a controller it's works but if i put it in a model class it didn't. the problem is in the session["user"] = null; .

So how can i manage the session's variables in a model class?

Upvotes: 2

Views: 3054

Answers (2)

Electric Sheep
Electric Sheep

Reputation: 4330

This functionality should not be in a view model. The model should be used for passing data from controllers to views for displaying, and receiving submitted data from views.

See a question like What is a ViewModel in MVC to get a better explanation.

A logout function should be an action on a controller. Something like:

public ActionResult Logout()
{
    Session["user"] = null;

    // Redirect user to homepage
    return Redirect("/");
}

Upvotes: 2

Pascalz
Pascalz

Reputation: 2378

In class access by the current context :

HttpContext.Current.Session["user"]....

Upvotes: 2

Related Questions