2

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;
}
asked Apr 28, 2013 at 8:24
1

2 Answers 2

1

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.

answered Apr 28, 2013 at 8:32
1

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.

answered Apr 28, 2013 at 23:46
2
  • 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. Commented Jul 28, 2013 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. Commented Jul 28, 2013 at 6:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.