I’m really new to OOP and C# and I’m trying to understand, how I could write my code as DRY as possible. In my ASP.NET MVC 3 Application I have multiple actions (two in this example code) in a controller which all return a different ViewModel which are all inheriting the same BaseViewModel. This is because I need the same data on every action but with additional properties for each.
I know I could simply create a constructor for ActionOneViewModel which receives a ViewModel object. But is this the common way to do this? Or are there any alternatives?
View Models:
class BaseViewModel
{
public string Name { get; set; }
public List<User> Users { get; set; }
}
class ActionOneViewModel : BaseViewModel
{
public bool FooBar { get; set; }
}
class ActionTwoViewModel : BaseViewModel
{
public string PingPong { get; set; }
}
Controller Actions:
public ActionResult ActionOne ()
{
// this doesn't work (of course)
ActionOneViewModel model = (ActionOneViewModel)createViewModel();
model.FooBar = true;
return View(model);
}
public ActionResult ActionTwo ()
{
// this doesn't work (of course)
ActionTwoViewModel model = (ActionTwoViewModel)createViewModel();
model.PingPong = "blub";
return View(model);
}
private BaseViewModel createViewModel()
{
BaseViewModel model = new BaseViewModel();
//
// doing a lot of stuff here
//
return model;
}
How about: