1.A quick way is that you can create a new ViewModel that combines the properties from both DashboardPageViewMode
l and UserViewModel
.
Model
public class DashboardViewModel { public DashboardPageViewModel DashboardData { get; set; } public UserViewModel UserData { get; set; } }
Then use Partial View
/View Component
to reuse the component.
View
@model DashboardViewModel <header> @Html.Partial("_Navbar", Model.UserData) </header> <!-- Access DashboardPageViewModel properties --> <h2>@Model.DashboardData.Title</h2>
2.If the user-related data is common across multiple pages, you can retrieve it from a service. Create a service that provides the user-related data (e.g., the user nickname) and inject this service into your Dashboard page and Navbar component. This way, both components can access the necessary data independently.
Service
public interface IUserService { string GetUserNickname(); } public class UserService : IUserService { public string GetUserNickname() { // Logic to retrieve user nickname from database or elsewhere //just for easy demo sharing return "User123"; } }
Program.cs
builder.Services.AddScoped<IUserService, UserService>();
Inject the service to Partial View/View Component
@inject IUserService UserService @{ var userNickname = UserService.GetUserNickname(); } <div> <span>Welcome, @userNickname!</span> <!-- Other Navbar content --> </div>
3.Although not recommended for complex scenarios, you can use ViewData
or ViewBag
to pass additional data from your Controller/Razor Pages to the View. However, this approach can lead to less maintainable code and should be used sparingly.
@Html.Partial
? Check this for reference codeproject.com/Questions/1029939/… That way you can get whatever object you need and pass that as the partial view's modelPageModel
, build your own common ancestor for common user properties. Or a@model
can be an interface type.