我的一个控制器中有几种方法可以做到这一点:
ViewData["Customers"] = LoadCustomers(); ViewData["Employees"] = LoadEmployees(); ViewData["Statuses"] = LoadStatuses(); etc......
这是LoadCustomers(),但LoadEmployees,LoadStatuses和所有其他几乎完全相同的逻辑:
private static SelectList LoadCustomers() { IListcustomers; try { IServiceCallService scService = new ServiceCallService(); customers = scService.GetCustomers(); Customer c = new Customer { ID = "", Name = "-- Select a Facility --" }; customers.Insert(0, c); } catch { customers = new List (); Customer c = new Customer { ID = "", Name = "-- No Facilities on File --" }; customers.Insert(0, c); } return new SelectList(customers, "ID", "Name"); }
如何更好地编写此代码,以便每次添加新的选择列表时都不需要新方法?
看起来它可能是泛型的一个很好的候选者:
private static SelectList LoadItems() where T : new, ... { // Add any additional interfaces // that need to be supported by T // for your Load method to work, // as appropriate. IList items; try { IServiceCallService scService = new ServiceCallService(); results = scService.Get (); // You'll need to replace GetCustomers() with // a generic Get method. // ... } catch // Really needed? What are you trying to catch here? (This catches { // everything silently. I suspect this is overkill.) // ... } return new SelectList(items, "ID", "Name"); }