Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the business logic that goes into creating a view model is quite complex I generally extract it into a helper method that I can test independently of the controller. </p> <p>However, that aside, your creation of the view model is perfectly fine within the controller as it is. As has already been noted, how your generating the select list could be made much simpler (not to mention reusable).</p> <p>Here is a ToSelectList extension of IEnumerable along with an example of usage: </p> <pre><code>public static List&lt;SelectListItem&gt; ToSelectList&lt;T&gt;( this IEnumerable&lt;T&gt; enumerable, Func&lt;T, string&gt; value, Func&lt;T, string&gt; text, string defaultOption) { var items = enumerable.Select(f =&gt; new SelectListItem() { Text = text(f) , Value = value(f) }).ToList(); if (!string.IsNullOrEmpty(defaultOption)) { items.Insert(0, new SelectListItem() { Text = defaultOption, Value = string.Empty }); } return items; } </code></pre> <p>Within your view model you could add a property like so:</p> <pre><code>IEnumerable&lt;SelectListItem&gt; Employees { get; set; } </code></pre> <p>Within your controller (i'm assuming that your repo is returning IEnumberable):</p> <pre><code>var employees = new IEnumerable&lt;Employee&gt;(); using (var gr = new GenericRepo&lt;Employee&gt;()) { employees = gr.Get(); } vm.Employees = employees.ToSelectList(x=&gt;x.FirstName + " " + x.LastName, x=&gt;x.Id, "-- Select Employee --") </code></pre> <p>And then to setup your drop down list in the view it would look something like:</p> <pre><code>@Html.DropDownListFor(model =&gt; model.EmployeeId, Model.employees) </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