Xaxum
Xaxum

Reputation: 3675

How to AccessSimpleMemberShipprovider properties of current user ASP.net MVC4

I have a razor .cshtml view in MVC4 and I want to print a field of my userprofile class. I understand I can get the Username from User.Identity.Name but I don't know how to access the other properties of the currently logged in user in the partial. Do I need to do this in my controller and reference it in my view? If so is there a controller that is available to all views so I am not setting this variable in every controller? Is there a simple way to access the current users properties as defined in the UserProfile model class right in the view? To give some context. I have my model as...

 public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }

        //Added to round out requirements for site user profile
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Site { get; set; }
    }

I need to access the FirstName in the view. If I get it in the controller then I will need to do it in all controllers since this is a page partial for all pages.

Upvotes: 1

Views: 1212

Answers (2)

Xaxum
Xaxum

Reputation: 3675

I decided to put it in a session variable since it is not critical, sensitive, or effects the stability of the application. In my controller on login or registration I set the session variable with...

var context = new UsersContext();
var curuser = context.UserProfiles.First(p => p.UserName == model.UserName);
Session["FName"] = curuser.FirstName;

I got this from Pro ASP.NET MVC and from this post. And in my Razor view I use this derived from this post.

@HttpContext.Current.Session["FName"].ToString()

Upvotes: 1

IMLiviu
IMLiviu

Reputation: 1016

In the controller action that is serving the partial view put FirstName in the ViewBag.
If there are more properties that you would like to return then create a ViewModel for them and make the controller action return that.

Upvotes: 0

Related Questions