ASP.net MVC共享方法

时间:2015-10-07 10:40:27

标签: c# asp.net-mvc methods

我有两种方法使用不同的视图模型,但逻辑相同。目前我已将它们复制并粘贴到各自的控制器中。以某种方式分享这些方法的任何方式?

歌曲控制器:

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");
    }

1 个答案:

答案 0 :(得分: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。您还必须使用DBHelper方法创建GetElements类,该方法根据类型从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;
        }
    }
}