Best way to show account information in layout fil

2019-05-31 06:36发布

问题:

I am using MVC3, and have a Layout file that is common for all of my Views. In the layout file, I would like to show some information regarding the currently logged in user.

I got it working now, but the only way I found out how to is to set some ViewBag fields in the actions methods, and pick them up in the layout file. This means that I will have to the the ViewBag fields from all my action methods, or at least make a method that sets them, and call this method from all my action methods.

Are there any central way to get this done? The absolute best is to do it once for the layout file in one place, but if no other option one place per controller might be good enough.

回答1:

The right way is to call Html.RenderAction() inside the layout file, where you want the user-specific details. Then create a suitable Action method somewhere which reads the user's account details and returns them as a view (partial view) or as raw html (return Content("...")).

That way, you can also benefit the ability to cache the layout page and keep the user's account details region uncached (since it's obviously different for every user).

Setting a ViewBag is not a good idea, it's not strongly type and it breaks the correct schema of MVC.