2

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?

1
  • 1
    Yes that's fine, no there is no guidelines. This is basic object orientation. Nothing to do with MVC. MVC is a presentation pattern (not a technology), it is concerned with presenting data to a UI. It has nothing to do with how your organise your business logic, etc. Commented Aug 1, 2018 at 10:04

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Seconded to Prefer composition over inheritance. Inheritance should always be used with caution for fear of making a rod for your own back later on
Yes, I also prefer composition, but I miss mixins in C#. Without them the composition is a bit messy. You have two options: expose the inner model or create a lot of "wrapping" code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.