I am using Linq To Sql to populate Html.DropDownLists in a few different forms with code like;
ViewData["EmployeeId"] = new SelectList(EmployeeRepository.Employees.ToList(),
"EmployeeId", "FullName");
This all works just fine but I have this same code all over the controller for the get ActionResult, then the same thing in the post ActionResult. It does not seem to matter if this is in the Model or the Controller it still has to get sent to the View and I still end up repeating this code. So in keeping with “Dont Repeat Yourself” mantra does anyone have any ideas on how to contain/refactor this code in one place. Would it be better to do all this in the View? Thanks to all the contributors on SO.
One way to solve it is to create a SelectList (or List) property on your model. When you new up a model, cast your employees into this property:
Now, in your view reference the property
You shouldn’t need this property in your controller because its used to give the user options to choose from. It is not an indicator of user selection.
hth