Note that there are some explanatory texts on larger screens.

plurals
  1. POWhere should code to build view models go?
    text
    copied!<p>When building a view model in asp.net's MVC3, where should the code go to instantiate the objects of that view model? I am doing it mostly in the controller right now, aside from the code to query the database. Here is an example in code:</p> <p>View Model:</p> <pre><code>public class WorkListVM { //list for employees [Display(Name = "Select A Employee")] [Required] public int? EmployeeId { get; set; } public GenericSelectList EmployeeList { get; set; } } </code></pre> <p>Controller Code:</p> <pre><code> //build view model var vm = new WorkListVM(); //build employee list vm.EmployeeList = new GenericSelectList(0,"-- Select Employee --"); var employees = new List&lt;Employee&gt;(); using (var gr = new GenericRepo&lt;Employee&gt;()) { 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); } </code></pre> <p>Generic Select List is a simple class to hold the data that goes in the helper <code>@html.dropdownfor</code>'s <code>SelectList</code>. I build these selectlist's, and also build similar data configurations for view models inside of the controller code. The controller hosting this code has a total of 109 lines of code, so it is not huge or out of control. However, I am always striving to reduce redundancy and sometimes the code in <code>//build employee list</code> ends up being copy pasted (ugh, i hate copy paste) into other controllers.</p> <p>Is there a better place to have this code? Should I maybe be using the factory pattern to build the data for these selectlists / other view data objects?</p> <p><strong>EDIT</strong></p> <p>Thanks for all your help. Here is what I ended up doing. I ended up making a method inside the generic select list class very similar to the .ToSelectList(...) suggested by Richard and Jesse:</p> <pre><code> public class GenericSelectList { public List&lt;GenericListItem&gt; Values { get; set; } public int StartValue { get; set; } public string Message { get; set; } public GenericSelectList(int StartValue = 0, string Message = "select") { Values = new List&lt;GenericListItem&gt;(); this.StartValue = StartValue; this.Message = Message; } public void BuildValues&lt;T&gt;(List&lt;T&gt; items, Func&lt;T, int&gt; value, Func&lt;T, string&gt; text) where T : class { this.Values = items.Select(f =&gt; new GenericListItem() { Id = value(f), DisplayFields = text(f) }).ToList(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload