Maher
Maher

Reputation: 501

How do I share code among controllers of different models?

How do I share code among controllers of different models?

In a 'super' controller action, I want to be able to figure out which controller (route) was called, and using that route name load the corresponding model, and use that model to query the database to pass to the view.

I can easily do this in Ruby on Rails, does MVC allow such a thing?

Upvotes: 3

Views: 173

Answers (4)

Wraith404
Wraith404

Reputation: 92

Think of your models as data structures, simple classes. They should have properties of course, but typically not code. The code should be organized elsewhere so that it can be shared.

How depends on the nature of the code you want to share. If it's controller level logic, related to model or view manipulation for example, it might be best in a controller base class. If it's business logic it should be in a service. Think of services as a layer of business logic between your controllers and your repository or database (depending on if you are using IOC). Your services should be contained in a library project referenced by your site, so that any controller can reference them.

Your routing rules should land you in appropriate controllers based on naming conventions, invoking action methods. Those methods may call any code from other classes or referenced projects.

Upvotes: 0

Jeremy Bell
Jeremy Bell

Reputation: 2174

You could use Generics:

public abstract class GenericRepositoryController<TModel> : Controller
{
    private readonly IRepository<TModel> _repository;

    protected GenericRepositoryController(IRepository<TModel> repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var model = _repository.GetAll();
        return View(model);
    }
}

public class EmployeeController : GenericRepositoryController<Employee>
{
    public EmployeeController(IRepository<Employee> repository) : base(repository)
    {
    }
}

public class CustomerController : GenericRepositoryController<Customer>
{
    public CustomerController(IRepository<Customer> repository) : base(repository)
    {
    }
}

Upvotes: 1

Wouter de Kort
Wouter de Kort

Reputation: 39888

Couldn't you use a base class for all your controllers and add the logich do figure out the route in the base class?

Or extract the 'rule finding method' to a helper class and use that in each method.

Upvotes: 0

Chance
Chance

Reputation: 11285

Sure, you could have all routes point to a central controller if you so desired and then redirect. Alternatively, you could have a base controller that other controllers inherrited from that did this as well.

Upvotes: 0

Related Questions