tags:

views:

71

answers:

2

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.

+1  A: 

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:

 EmployeeRepository.Employees.Select(e => new SelectListItem 
     {Text=e.FullName,Value=e.EmployeeId}).ToList()

Now, in your view reference the property

Model.EmployeeList //the List<SelectListItem> containing your employees

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

kmehta
Thanks Robert, I like your solution much better than the way I am currently doing this. Cheers.
hankasu
A: 

Check out this link: http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx Hope this helps.

ali62b
That does help, thanks for you time ali
hankasu