When building a view model in asp.net MVC3, where should the code go to instantiate the objects of this view model? I am doing this mainly in the controller right now, except for the code to query the database. Here is a sample code:
View Model:
public class WorkListVM
{
[Display(Name = "Select A Employee")]
[Required]
public int? EmployeeId { get; set; }
public GenericSelectList EmployeeList { get; set; }
}
Controller Code:
var vm = new WorkListVM();
vm.EmployeeList = new GenericSelectList(0,"-- Select Employee --");
var employees = new List<Employee>();
using (var gr = new GenericRepo<Employee>())
{
employees = gr.Get().ToList();
}
foreach(var employee in employees)
{
var gl = new GenericListItem();
gl.Id = employee.EmployeeId;
gl.DisplayFields = employee.FirstName + " " + employee.LastName;
vm.EmployeeList.Values.Add(gl);
}
- , @html.dropdownfor SelectList. , . , , 109 , . , , //build employee list , (ugh, hate copy paste) .
? factory selectlists/ ?
. . , , .ToSelectList(...), :
public class GenericSelectList
{
public List<GenericListItem> Values { get; set; }
public int StartValue { get; set; }
public string Message { get; set; }
public GenericSelectList(int StartValue = 0, string Message = "select")
{
Values = new List<GenericListItem>();
this.StartValue = StartValue;
this.Message = Message;
}
public void BuildValues<T>(List<T> items, Func<T, int> value, Func<T, string> text) where T : class
{
this.Values = items.Select(f => new GenericListItem()
{
Id = value(f),
DisplayFields = text(f)
}).ToList();
}
}