views:

269

answers:

3

I'm using ASP.NET MVC and the Membership providers. How do I get the profile of a user in a view? any particular method to get it?

The template project out of the box access the username in this way:

<%= Html.Encode(Page.User.Identity.Name) %>

I'd like to have a similar way to access the profile data.

+2  A: 

In MVC, you shouldn't access the profile directly in the view. You should fill a model object with values of the user profile in the controller and use the view to render those values.

Mehrdad Afshari
That would mean that I would have to make a ViewModel for absolutely every View I have and add the membership data to it. I understand how that is pure MVC but I find it ugly and cumbersome. Furthermore, the built-in template shows how to access Page.User.Identity.Name to get the username, is the template wrong?
J. Pablo Fernández
Create a base ViewModel with the membership data and use that. If you need additional data for a specific view, inherit the base and add the specifics.
svinto
svinto: most of my views are fine with just the model, straight from the entity framework. Having a base ViewModel or not would mean to have a lot of extra classes, for each view more or less. Is that the elegant way?
J. Pablo Fernández
+1  A: 

Since Membership is handled at server side, if you want that information to be available at the View is either using your Session or the ViewData hash. So before you renders the page put the proper data or object as part of the ViewData or as part of the Session. If you are only using in one view, then I recommend ViewData.

Freddy
A: 

The way to access the user profile on MVC is through the Profile variable in the view, like this:

<%= Profile %>
J. Pablo Fernández

related questions