2015-10-07 73 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,请检查我的编辑。这是未经测试的代码,所以如果感觉不太对劲,那么请添加注释 –