Using TempData to pass a Model to an MVC Controller

There may be a better way, but…

I needed to store my user information, stored in the UserProfile class and, to reference it again on a subsequent user action. Rather than making another call, I stored it in TempData. In my Login action, I pull the user information from the database:

       public ActionResult Login(LoginModel model, string returnUrl) {
                using (UsersContext db = new UsersContext()) {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    TempData["User"] = user;
        }

And later, I once again reference my user database like so:

public ActionResult CoolLink(string a) {
    UserProfile model = (UserProfile)TempData["User"];
     …
}

I’m sure there is a very MVC way to do it, but I just wanted to get this done and get on with other problems. You can see the TempData definition on MSDN.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: