简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM