I have 2 ActionResults that return the same view with a DropDownList source
Public ActionResult Create()
{
var model = new ViewModel {
Entity = new Entity(),
Categories = GetCategories()
};
return View("Edit", model);
}
Public ActionResult Edit(int id)
{
var model = new ViewModel {
Entity = GetFromDatabase(id),
Categories = GetCategories()
};
return View(model);
}
I feel like I’m breaking the DRY principle, even if I’ve moved the population of the categories to a method. Is there a better way to go about this and only state where to get the Categories from once?
I think you are bit over concerned. This code looks fine for me. This is more readable. As long as you don’t have a a big performance issue, you don’t need to worry about that.
If you still want to avoid
GetCategoriescall in 2 places and you may put that into the constructor of your ViewModel class.It is up to you how to handle this. There are no written rules. Follow what you think is more readable and look clean. But personally, i would keep my ViewModel as simple POCO class without any of this constructor logic to load data. I would be happy with calling
GetCategoriesin both the action methods. To me, that looks clean and readable.