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");
}
我如何创建的getElements方法。我真的从来没有做过帮手,所以我不知道从哪里开始? –
您需要创建一个名为DBHelper的类,就像创建任何其他类一样。在里面你需要定义GetElements,它将接收一个应用程序数据库上下文和一个System.Type。基于System.Type收集元素。你需要使用if-elses来达到这个目的。 –
@MartinMazzaDawson,请检查我的编辑。这是未经测试的代码,所以如果感觉不太对劲,那么请添加注释 –