Martin Dawson
Martin Dawson

Reputation: 7656

ASP.net MVC Sharing methods

I have two methods that use different viewmodels but are the same logic. At the moment I have copied and pasted them into their respective controllers. Any way to share these methods somehow?

Song Controller:

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

Station Controller:

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

Edit: class so far:

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

Upvotes: 1

Views: 433

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76424

Create a class called BasicController and add the method to it, like this:

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

and modify your classes to inherit from BasicController. You will also have to create the DBHelper class with the GetElements method, which gathers the IEnumerable elements from db based on type.

EDIT: This is how you can create a helper:

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

Upvotes: 2

Related Questions