Ruben Aguilar
Ruben Aguilar

Reputation: 1235

Share code between areas ASP.net MVC

We have a ASP.net MVC application organized using different Areas. We are adding a new functionality that works across areas and we want to reuse some view models for this functionality in the different Areas.

We were thinking in a BaseViewModel and BaseViewModel builder classes in some "shared folder" and then implementing the subclasses in each Area.

Is this a good approach? Are there any guidelines to share code between Areas in ASP.net MVC?

Upvotes: 2

Views: 1144

Answers (1)

Georg Patscheider
Georg Patscheider

Reputation: 9463

Your approach sounds reasonable.

In our project, we have the shared ViewModels in {Project Root}\Models and the corresponding *.cshtml files in {Project Root}\Views\Shared.

The Area specific ViewModels reside in {Project Root}\Areas\{Area}\Models and their Views in {Project Root}\Areas\{Area}\Views.

As a side note, I would not introduce a BaseViewModel. Prefer composition over inheritance, this will make maintenance easier. If you need to display common data on different pages, introduce shared ViewModels and Partial Views for these common data, then add the Sub-ViewModels to the ViewModels of the pages and render them with @Html.PartialFor(). Here is an example of composition:

public class Models.PatientOverviewViewModel {
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
}

public class Areas.Patient.Models.PatientDetailsViewModel {
    public PatientOverviewViewModel Overview { get; set; }
    public string MobilePhone { get; set; }
}

~\Areas\Patient\Views\PatientDetails.cshtml:

@model Areas.Patient.Models.PatientDetailsViewModel
@Html.Partial("_PatientOverview", Model.Overview)
@Html.DisplayFor(m => m.MobilePhone)

~\Views\Shared_PatientOverview.cshtml:

@model Models.PatientOverviewViewModel
@Html.DisplayFor(m => m.Name)
@Html.DisplayFor(m => m.BirthDate)

Upvotes: 2

Related Questions