0

Good day. I encountered a problem while developing an asp.net core mvc application. The fact is that I have a Dashboard page for which the data is taken from the @model DashboardPageViewModel. Also, on each page I have a Navbar component in which there is a user nickname, which is also taken from the @model UserViewModel. But the system only allows uploading one model per page. Tell me how it is possible to solve the problem

I tried to combine the use of models in the class, but they are from too different areas. And the navbar is present on every page.

2
  • Maybe you should use a @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 modelCommentedApr 22, 2024 at 13:59
  • IMHO don't inherit from PageModel, build your own common ancestor for common user properties. Or a @model can be an interface type.CommentedApr 23, 2024 at 3:17

1 Answer 1

1

1.A quick way is that you can create a new ViewModel that combines the properties from both DashboardPageViewModel 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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.