Nick
Nick

Reputation: 5872

Sharing identical controller code between areas in ASP.NET MVC

I have two idential controllers in two seperate areas within my project.

The only difference between the two is the base controller.

  1. BrowsingSessionController : Area1BaseController
  2. BrowsingSessionController : Area2BaseController

The controllers themselves are quite meaty and return Views or RedirectToActions based on conditions.

I don't want to repeat myself in terms and wish to adhere to the DRY principle and wondered how to maintain the controller structure but avoid repeating the code.

Sample of Method

BrowsingSessionControllerContent

...
case ("byexpiry"): // Expiry Grid

    currentTemplateModel._TemplateExpiry =
        _browsingSessionTemplateRepository.GetBrowsingSessionLeadExpiryTemplateById(currentTemplateModel.Id);
    return View("SessionExpiryGrid",
                new SessionExpiryGridModel()
                {
                    ActiveBrowsingSessionTemplate = currentTemplateModel,
                    SessionGuid = guid
                });
...

Upvotes: 1

Views: 1230

Answers (1)

Oved D
Oved D

Reputation: 7442

It's often better to use composition rather than inheritance to share logic between controllers.

You could use static utility classes to encapsulate common logic, and call that from your controller code.

That logic would exist in the base area.

Upvotes: 1

Related Questions