Several views from my project have the same dropdownlist...
So, in the ViewModel from that view I have :
public IEnumerable Fo
What about a Prepare
method in a BaseController
?
public class BaseController : Controller
{
///
/// Prepares a new MyVM by filling the common properties.
///
/// A MyVM.
protected MyVM PrepareViewModel()
{
return new MyVM()
{
FooDll = GetFooSelectList();
}
}
///
/// Prepares the specified MyVM by filling the common properties.
///
/// The MyVM.
/// A MyVM.
protected MyVM PrepareViewModel(MyVM myVm)
{
myVm.FooDll = GetFooSelectList();
return myVm;
}
///
/// Fetches the foos from the database and creates a SelectList.
///
/// A collection of SelectListItems.
private IEnumerable GetFooSelectList()
{
return fooRepository.GetAll().ToSelectList(foo => foo.Id, foo => x.Name);
}
}
You can use this methods in the controller:
public class HomeController : BaseController
{
public ActionResult ActionX()
{
// Creates a new MyVM.
MyVM myVm = PrepareViewModel();
}
public ActionResult ActionY()
{
// Update an existing MyVM object.
var myVm = new MyVM
{
Property1 = "Value 1",
Property2 = DateTime.Now
};
PrepareViewModel(myVm);
}
}