Search code examples
c#asp.net-mvcmodel-view-controllerasp.net-mvc-2application-design

Good practice to have a data-only controller in MVC?


I'm using ASP.NET MVC2 and have various controllers in various areas.

In many of these I need to select a value from a list of values contained in a database; selecting a product or an employee for example.

I'm currently thinking of having a controller dedicated to getting these lists of things for use with dropdownlists etc. This controller would simply query the DAL and serve up JSON objects to be loaded with an ajax call on any view that needed them.

My only concern with this is that my view will be getting data from different controllers at once.

Am I right to be concerned? Is there a better way of setting this up, maybe creating a Product/Employee class especially to create a shared strongly typed partial view from?


Solution

  • Create another class which acts as a middle layer between your controllers and data access code. You can call this class methods from differnt controllers now.

    public class ItemService()
    {
     public static List<Items> GetItems()
     {
        var items=yourRepositary.GetItems();
        return items;
     }
    }
    

    You can call it from your different controllers now

    public ActionResult GetItems()
    {
      var items=ItemService.GetItems();
      return Json(items,JsonRequestBehavior.AllowGet);
    }