0

I have a Controller where on the Create action I need the user ID.

Here's the controller.

    public ActionResult Create(MyCreateViewModel model)
    {
        if (ModelState.IsValid)
        {
            var myobject = new MyObject
            {
                Attrib1 = DateTime.Now.Date,
                Attrib2 = model.Etichetta,
                UserId = // I need the user ID...
            };

            // Save the object on database...                

            return RedirectToAction("Index");
        }
        return View(model);
    }

I'm using the UserProfile table provided with the SimpleMembership of MVC 4.

Which is the best practice in MVC 4 to manage the userID across the application?

Do I have to include a User attribute inside every Entity class?

Should I use a Session[] variable or what?

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
Cheshire Cat
  • 1,941
  • 6
  • 36
  • 69

1 Answers1

2

You can use this line to get the userId from the UserProfiles table.

var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);

You can also use this function to get the users complete profile, including any custom columns you may be populating.

public static UserProfile GetUserProfile()
        {
            using (var db = new UsersContext())
            {
                var userId = WebSecurity.GetUserId
                            (HttpContext.Current.User.Identity.Name);
                var user = db.UserProfiles
                             .FirstOrDefault(u => u.UserId == userId);
                if (user == null)
                {
                    //couldn't find the profile for some reason
                    return null;
                }
                return user;
            }
        }
Eonasdan
  • 7,563
  • 8
  • 55
  • 82
  • The `WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name)` works. If I would like to use the function, where should I put it? Not inside the UserProfile model class I guess, or I it will be translated into a new attribute on the table... Right? – Cheshire Cat Jul 08 '13 at 12:31
  • that's an OOTB function from the `SimpleMembership` or `WebMatrix`. I have a class file (called `UserHelpers`) that has both of these snippets in it for easy accessibility. – Eonasdan Jul 08 '13 at 12:55
  • I also get another solution on this answer http://stackoverflow.com/questions/14630158/asp-net-mvc-4-how-to-manage-userid-and-user-content-inside-controllers. You can use `WebSecurity.CurrentUserId` to get the ID or `WebSecurity.CurrentUserName` to get the name. – Cheshire Cat Jul 16 '13 at 13:46
  • nice! Thanks for that shortcut – Eonasdan Jul 16 '13 at 13:56