2009-03-25 13 views
4

私はこれを行うに私のコントローラのいずれかで、いくつかの方法があります:ここでこのコードをリファクタリングするには、ASP.NET MVCのDRY原則をどのように使用できますか?

ViewData["Customers"] = LoadCustomers(); 
ViewData["Employees"] = LoadEmployees(); 
ViewData["Statuses"] = LoadStatuses(); 
etc...... 

をLoadCustomers()、しかしLoadEmployees、LoadStatusesおよび他のすべてが事実上まったく同じロジックですされています

private static SelectList LoadCustomers() 
    { 
     IList<Customer> customers; 
     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>(); 
      Customer c = new Customer 
      { 
       ID = "", 
       Name = "-- No Facilities on File --" 
      }; 
      customers.Insert(0, c); 
     } 

     return new SelectList(customers, "ID", "Name"); 
    } 

このコードをもっとうまく書くにはどうすればいいですか?新しい選択リストを追加するたびに新しいメソッドは必要ありません。それはジェネリック医薬品のための良い候補であるかもしれないようにこれが見えます

答えて

5

private static SelectList LoadItems<T>() where T : new, ... 
{            // Add any additional interfaces 
               // that need to be supported by T 
               // for your Load method to work, 
               // as appropriate. 
    IList<T> items; 
    try 
    { 
     IServiceCallService scService = new ServiceCallService(); 
     results = scService.Get<T>(); // You'll need to replace GetCustomers() with 
             // a generic Get<T> 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"); 
} 
+0

あなたはまた、そのtry/catchブロックを取り除く必要があります。それはどれほど深刻であっても、すべての例外を食べるでしょう。致命的なエラーが発生した場合は、続行しないでください。 –

0

また、より機能的なアプローチを試みることができます。

public IList<T> Load<T>(Func<IList<T>> getList, T prependItem) 
{ 
    var list = getList(); 
    list.Insert(0, prependItem); 
    return list; 
} 

使用法: - SelectListの

var prependItem = new Customer { ID = "", Name = "-- Select a Facility --" }; 
ViewData["Customers"] = new SelectList(
    Load(new ServiceCallService().GetCustomers(), prependItem), 
    "ID", "Name"); 

このアプローチも構築されているものの細部からのリストの構築を分離します。

0

私はさらに行くとコントローラのコードでこれを記述します:

ビューで
ViewData["Customers"] = new SelectList(
     new ServiceCallService().GetCustomers(), 
     "ID","Name") 

この

<%= Html.DropDownList("Customers", 
    ((SelectList)ViewData["Customers"]).Count() > 0 ? 
    "-- Select a Facility --" : "-- No Facilities on File --") %> 
関連する問題