tags:

views:

70

answers:

2

I need to get the user's name and ID to be accessible in my view. When I use Page.User.Identity.Name, I get the email I use to authenticate it. This is how I go about authenticating the user from my controller:

if (!userService.ValidateUser(model.Email, model.Password))
      FormsAuthentication.SetAuthCookie(model.Email, false);

How can I be able to do: Page.User.Identity.UserId or Page.User.Identity.FirstName?

+1  A: 

The base MVC controller has a User property you can access in your actions. Just attach the properties you need to your view model.

public ActionResult Index()
{  
   var user = new UserViewModel();
   user.FirstName = this.User.Identity.FirstName;
   ViewData["UserDetails"] = user;
   // ...
   return View(theOtherModel);
}

In the site.master:

<% var userModel = ViewData["UserDetails"] as UserViewModel; %>
Hello <%: userModel.FirstName  %>!
Ryan
some more details please, or example code. Thanks.
Shawn Mclean
The `Controller.User` would be the same reference that `Page.User` is, as well.
Andrew Barber
What if I already passed a model to the view? How can i pass another? It should also be accessible in the site.master
Shawn Mclean
If you want it accessible in the master view then I would put it in the ViewData collection.
Ryan
This method requires that controller action to be called for it to show. I want to do something like that in my logon action that will spread across all controllers. So any page I go on, I will see the FirstName of the user.
Shawn Mclean
You could use an action filter and put it on each controller. If you're using MVC3 you could use a global action filter. I don't have any sample code for this.
Ryan
A: 

Shaun, here´s an idea:

First, you can create an action filter so that you inject the object that represents your user in the ViewData collection. You can apply this attribute to your controller or to the actions.

public class AddUserToViewDataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var email = filterContext.HttpContext.User.Identity.Name;

        var user = _userService.GetUser(email);

        filterContext.Controller.ViewData["CurrentUser"] = user;
    }
}

Some improvements should be made of course, this is just an idea.

Another idea is to create a base controller class (so that your controllers extend it) and in that controller you can have a method (e.g. GetCurrentUser) that does the same as in this filter (i.e. load the user from the DB). You can apply some caching like for example, saving the user object in the HttpContext.Items collection.

Cheers.

uvita