I am developing an ASP.Net MVC 3 Web application and believe my method of returning a list of items to a drop down list in the View is a bit long winded. Let me explain.
I have a ViewModel which contains an Equipment Entity and a SelectList to display a list of Categories.
public class AddEquipmentViewModel
{
public Equipment equipment { get; set; }
public SelectList categoryList { get; set; }
}
In the GET create method of my Equipment Controller, I return my ViewModel to the view, see below:
//Add new select list item named 'Please select option' to the top of list
var categoryList = categoryService.GetAllCategories();
var categorySelectListItems = categoryList.Select(c => new SelectListItem { Value = c.categoryID.ToString(), Text = c.categoryTitle }).ToList();
categorySelectListItems.Insert(0, new SelectListItem { Text = "Please select option", Value = string.Empty });
AddEquipmentViewModel viewModel = new AddEquipmentViewModel
{
equipment = new Equipment(),
categoryList = new SelectList(categorySelectListItems.ToList(), "Value", "Text")
};
I know I could discard the extra code before I create an instance of my ViewModel and just assign my Category List to the relevant ViewModel property like so
categoryList = new SelectList(categoryService.GetAllCategories(), "categoryID", "categoryTitle")
However, this then just returns a list of categories to my drop down list in my View, whereas, I would like to add a new SelectListItem, ie, "Please select option".
I just feel that my approach to manually adding a new SelectListItem to my SelectList is a bit cumbersome and I would greatly appreciate if someone could share a better method?
Thanks for your time.