Question

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?

Was it helpful?

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);
}

OTHER TIPS

Best solution imho is to create a custom ActionFilterAttribute that populates the ViewData dictionary with whatever data you need to render on the views. You can then create extensions for ViewDataDictionary to access this info in a type-safe manner from the views, or throw an exception if the ViewData does not contain the data (ie prompting you to add the action filter attribute above your controller method). Using inheritance could get you in a mess further up the road.

Another approach would be to use a base class controller that implements this common functionality, then inherit other concrete controllers (paired with views) from this.

This approach would support a situation where there are lots of different lists, or the lists needed building dynamically in response to input paramters.

The ActionFilterAttribute approach might be better suited to situations where there are fewer, more static lists.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top