I have MVC 3 C# project with Razor engine. What are the ways and, I guess, the best practices to write dynamic data to the _Layout.cshtml?
For example, maybe I’d like to display user’s name in the upper right corner of my website, and that name is coming from Session, DB, or whatever based on what user is logged in.
UPDATE: I’m also looking for a good practice on rendering certain data into the element of the Layout. For example, if I need to render a specific CSS file depending on the logged-in user’s credentials.
(For the example above, I thought of using Url Helpers.)
The default internet application created by visual studio use _LogOnPartial.cshtml to do exactly this.
The user Name value is set in the LogOn action of the HomeController
Code for _LogOnPartial.cshtml
User.Identity is part of the aspnet Membership provider.
Code for the _Layout.cshtml
Code for the AccountController Logon Action
Code for ApplicationViewPage class
The above code allow me to have a ViewBag.LayoutModel that hold an instance of my LayoutModel class in every page.
Here is a code for my LayoutModel class
Here is the code to the View
Refer to the following question for more detail. Make sure you modify your web.config as described there: How to set ViewBag properties for all Views without using a base class for Controllers?