How to show member data on each page?

I want to be able to display various details about the member ("user") on each page, i.e. partial, which displays some login information.

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

stackoverflow example

Since we like to stick with ViewModels, it seems reasonable to populate the ViewModel and pass it to each page. The ViewModel will contain a member object (and possibly other data).

One way to do this is to create an abstract “base” ViewModel class and have all the other ViewModels that you usually use inherit from it. This seems a little cumbersome, since every ViewModel you create must inherit 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 was informed that this is not recommended, because it is "not very MVC-ish". That is, this does not correspond to the natural way of working in MVC.

How can I solve this problem? Is ViewModels the Way?

C # or VB.NET are acceptable.

+4
source share
2 answers

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

+6
source

As a rule, I avoid ViewBag , I will make an exception when transmitting user information. In my base controller, I set ViewBag.UserInfo for onActionExecuted and becomes available for all views with the following:

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

If you go with interfaces or an abstract base, you need to make sure that EVERYTHING with whom you view models fill in the user fields. This really increases the overhead for your viewing models.

+1
source

Source: https://habr.com/ru/post/1487178/


All Articles