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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With