I want to display information about the logged in user (username, company name, number of notifications, etc) in the layout and/or partial views. These will be common on every page. Is there a trick for getting this data to them, or is it a case of extending each model to have this information in them?
To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.
To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.
Partial views shouldn't be used to maintain common layout elements. Common layout elements should be specified in _Layout. cshtml files. Don't use a partial view where complex rendering logic or code execution is required to render the markup.
A layout is something that we can include once in a single page and we can use the same layout to any number of pages. A partial view is something that we can include the same content any number of times in a single page(where it is required) and can be used in any number of pages.
I would suggest you can go for a child action and invoke it from the layout, By this way you can avoid carry out the information in all the view models.
Ex.
Child action
public class UserController
{
[ChildActionOnly]
public PartialViewResult UserInfo()
{
var userInfo = .. get the user information from session or db
return PartialView(userInfo);
}
}
Partial View
@model UserInfoModel
@Html.DisplayFor(m => m.UserName)
@Html.DisplayFor(m => m.CompanyName)
...
Layout view
<header>
@Html.Action("UserInfo", "User")
</header>
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