Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 811
Rowan Freeman Avatar asked Mar 23 '23 12:03

Rowan Freeman


2 Answers

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

like image 172
Kazi Manzur Rashid Avatar answered Mar 26 '23 03:03

Kazi Manzur Rashid


While as a rule I avoid ViewBag, I'll make an exception when passing user info. In my base controller I'll set the ViewBag.UserInfo for onActionExecuted and it becomes available to all views with the following:

@{
    var userInfo = ViewBag.UserIno as UserInfo;
}

If you go with interfaces or abstract base, you'll need to make sure ALL you view models populate the user fields. That really adds to the overhead for your view models.

like image 45
Jasen Avatar answered Mar 26 '23 02:03

Jasen