Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model?

I would add that I have other controller methods that will read this session value later.

  public ActionResult AddFriend(FriendsContext viewModel)
  {
        if (!ModelState.IsValid)
        {                
            return View(viewModel);
        }

        // Start - Confused if the code block below belongs in Controller?

        Friend friend = new Friend();
        friend.FirstName = viewModel.FirstName;
        friend.LastName = viewModel.LastName;
        friend.Email = viewModel.UserEmail;            

        httpContext.Session["latest-friend"] = friend;

        // End Confusion

        return RedirectToAction("Home");
    }

I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.

public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext)
{
    httpContext.Session["latest-friend"] = friend;
}


public static Friend GetLatestFriend(HttpContextBase httpContext)
{
    return httpContext.Session["latest-friend"] as Friend;
}
share|improve this question
    

2 Answers 2

If it was me, I would create a new class called SessionManager (or something), where you can pass through your data to save the latest friend and retrieve it. That way you've got one spot where all of your session handling is done.

share|improve this answer

Storing data should be done in the model:

The way the data is stored is not important to the controller, so it should be handled in the model. So, when you change the storage from session to a database for whatever reason, you will just have to change the model.

share|improve this answer
1  
I don't agree: the controller is supposed to be your gateway to the presentation and the session is presentation (management). If you already have the code in your controllers it's easier to integrate it to a repository. –  Jeroen Vannevel Jul 28 '13 at 2:08
    
I've had to move session data out of a session handler and into a data store and always make a session model now. –  siva.k Jul 28 '13 at 6:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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