0

Possible Duplicate:
How to assign Profile values?

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.

Community
  • 1
  • 1
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

3 Answers3

2

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.

Community
  • 1
  • 1
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 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? – Pablo Fernandez Aug 02 '09 at 12:23
  • 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. – Svante Svenson Aug 02 '09 at 12:39
  • 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? – Pablo Fernandez Aug 02 '09 at 13:28
  • @J. Pablo Fernández, if it is a common piece of data that is common to many views, but different to the model from the entity framework, and you don't want to use view models, then perhaps do what Freddy suggests, and include it in the ViewData dictionary. I believe you could write an action filter to populate this information into the ViewData/ViewBag dictionary to keep it DRY [ see http://stackoverflow.com/questions/2261768/best-way-to-populate-viewdata-for-dropdownlists-in-asp-net-mvc ] – jamiebarrow Aug 22 '11 at 15:57
2

Membership is handled at the server side; if you want that information to be available to the View, then use either your Session or the ViewData dictionary. Before you render the page, put the proper data or object into the ViewData dictionary, or add it as part of the Session. If you are only using in one view, then I recommend ViewData.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Freddy
  • 3,064
  • 3
  • 26
  • 27
1

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

<%= Profile %>
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622