0

I am new to MVC and I have very simple problem. When user login to my application I need to create a specific object (model) for the user for eg UserObject.

This object is unique to current logged in user and should only be disposed when user click on logout. I don’t know how to maintain the lifetime of the object. As if I create object in Action method of controller class then as soon as the request is finished I lose the reference of the object.

How this should have been done?

3
  • 1
    Using sessions.
    – CodeCaster
    Dec 12, 2014 at 11:39
  • Why do you want to keep a given instance alive, the usual way is to fetch a new instance from the data store when you need it based on user id. Dec 12, 2014 at 11:44
  • If you want to persists any data as long as the user session exists it is always suggested to use session which is long live or may use TempData which MVC provides.
    – Venkatesh
    Dec 12, 2014 at 14:02

3 Answers 3

0

The lifetime of your models are only going to be as long as the request. So each time the user goes to another page or refreshes, the MVC framework is going to instantiate a new controller (and model within). Otherwise your server would have a ton of static objects floating around in memory which would use up a lot of resources and wouldn't scale.

In order to manage state, you are going to need to use other methods such as sessions/cookies and a database.

So let's say the user logs in via /User/Login. This routes the request to an action named UserController.Login().

Inside this action, it instantiates a UserModel.

public ActionResult Login(string username, string password) {
    var userModel = new UserModel();
    if (userModel.Authenticate(username, password)) {
        // Setup your session to maintain state
        Session["username"] = username;
    } else {
        return View("Login");
    }
    return View("LoginComplete");
}

You might want the user model to actually create the session, but I've shown it here for clarity.

The user model authenticates the user, and then you create a session just like you would in a traditional non-MVC site.

Then in subsequent requests, you will want to authorize the user, and use any session data you have to retrieve state information.

public ActionResult SuperSecretPlace() {
    var userModel = new UserModel();
    string username = Session["username"]
    var user = userModel.GetUserByUsername(username);
    if (user == null) throw new HttpException(401, "User is not authorized.");
    return View("SuperSecretPlace", user);
}

In the action above, the UserModel might do something like query a database to retrieve the user's data so you can pass it in to the corresponding view.

If you want to make life easier, you might want to just use .NET's built in forms authentication: http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF

For more info about the lifecycle of MVC:

0

Actually what you are trying to achieve is passing model from controller to controller which is not possible. When an action is executed the context of the model object is disposed at the view and it can cannot be passed from controller to controller. You have to create a new object repopulate it and use it to achieve the goal in different controller.If you need the data to be persisted you can use sessions but still you need to create an object of the model in every controller.

The following image is for your reference as to see what to use when passing data between model-view-controller. Please feel free to ask if you need more information on this.

Data passing in MVC

0

As opposed to the other aswers I would not use session as it has quite some disadvantages (scalability, pessimistic concurrency which blocks concurrent calls, app pool recycling...). Why you should not use session is documented in a lot of places like here or here.

Instead, I would store it in a cookie.

However, be sure to not store confidential or sensitive data. Whatever you use (cookies or session), it can be tampered with or stolen. If you are dealing with sensitive information, you need other solutions. Read also more about secure cookie solution here.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.