2015-10-07 75 views
1

我有兩種方法使用不同的視圖模型,但邏輯相同。目前我已經將它們複製並粘貼到它們各自的控制器中。任何方式來分享這些方法?ASP.net MVC共享方法

宋控制器:

public JsonResult IncrementViews(int id) 
    { 
     using (ApplicationDbContext db = new ApplicationDbContext()) 
     { 
      PublishedSongViewModel song = db.PublishedSongs.Single(x => x.Id == id); 
      song.UniquePlayCounts++; 
      db.SaveChanges(); 
      return Json(new { UniquePlayCounts = song.UniquePlayCounts }, JsonRequestBehavior.AllowGet); 
     } 
    } 

站控制器:

public JsonResult IncrementViews(int id) 
     { 
      using (ApplicationDbContext db = new ApplicationDbContext()) 
      { 
       RadioStationViewModel station = db.RadioStations.Single(x => x.Id == id); 
       station.UniquePlayCounts++; 
       db.SaveChanges(); 
       return Json(new { UniquePlayCounts = station.UniquePlayCounts }, JsonRequestBehavior.AllowGet); 
      } 
     } 

編輯: 類到目前爲止:

public static IEnumerable<Type> GetElements(ApplicationDbContext db, Type type) 
    { 
     if (type == typeof(SongsController)) 
      return (IEnumerable<Type>)db.PublishedSongs; 
     else if (type == typeof(RadioStationsController)) 
      return (IEnumerable<Type>)db.RadioStations; 
     else 
      throw new Exception("Controller not found, DBHelper"); 
    } 

回答

2

創建一個名爲BasicController類和方法添加到它,像這樣:

public class BasicController { 
    public JsonResult IncrementViews(int id) 
    { 
     using (ApplicationDbContext db = new ApplicationDbContext()) 
     { 
      var element = DBHelper.GetElements(db, this.GetType()).Single(x => x.Id == id); 
      element.UniquePlayCounts++; 
      db.SaveChanges(); 
      return Json(new { UniquePlayCounts = song.UniquePlayCounts }, JsonRequestBehavior.AllowGet); 
     } 
    } 
} 

並修改你的類以繼承BasicController。您還必須使用GetElements方法創建DBHelper類,該方法根據類型從db收集IEnumerable元素。

編輯:這是你可以創建一個幫助:

public class DBHelper { 
    public static IEnumerable GetElements(ApplicationDbContext db, System.Type type) { 
     if (type == typeof(SongController)) { 
      return db.PublishedSongs; 
     } else if (type == typeof(StationController)) { 
      return db.RadioStations; 
     } 
    } 
} 
+0

我如何創建的getElements方法。我真的從來沒有做過幫手,所以我不知道從哪裏開始? –

+0

您需要創建一個名爲DBHelper的類,就像創建任何其他類一樣。在裏面你需要定義GetElements,它將接收一個應用程序數據庫上下文和一個System.Type。基於System.Type收集元素。你需要使用if-elses來達到這個目的。 –

+0

@MartinMazzaDawson,請檢查我的編輯。這是未經測試的代碼,所以如果感覺不太對勁,那麼請添加註釋 –