Search code examples
asp.net-mvcrazor-2

How do I show member details on every page?


I want to be able to show various details about a member ("user") on every page - i.e. a partial that displays some login details.

For example, stackoverflow shows my username, my reputation and badges on every page.

stackoverflow example

Since we like to stick with ViewModels, it seems sensible to populate a ViewModel and pass it to every page. The ViewModel would contain the member object (and perhaps other data).

One way to do this is to create an abstract "base" ViewModel class and have all other ViewModels that you normally use inherit from it. This seems a little cumbersome, since every ViewModel that you make has to inhertit from the base. Annoying?

Another way is to use HttpContext.User.Identity.

Another way is to create a custom WebViewPage.

But for these two possibilities I've been informed that it's not recommended because it's "not very MVC-ish". That is, it doesn't conform to the natural way we do things in MVC.

How might I solve this problem? Are ViewModels the way to go?

C# or VB.NET are acceptable.


Solution

  • Create a controller that returns user info in a partial, call the controller with Html.Action() in your layout page. A blog post I wrote long time ago which you may can check: http://kazimanzurrashid.com/posts/viewdata-or-viewbag-avoid-dependency-pollution-in-asp-dot-net-mvc-controller