ch0va
ch0va

Reputation: 1

Multiple models in one view ASP.net core mvc

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.

Upvotes: 0

Views: 281

Answers (1)

Rena
Rena

Reputation: 36725

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.

Upvotes: 1

Related Questions