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,請檢查我的編輯。這是未經測試的代碼,所以如果感覺不太對勁,那麼請添加註釋 –