I use this part of code to get informations from my database, using Entity Framework, and add all of it in a IEnumerable property for, at the end, a DropDownListFor display.
I need to use that kind a code many time so I would like to make it the most powerfull at the begenning.
public IEnumerable<SelectListItem> Functions { get
{
List<SelectListItem> result = new List<SelectListItem>();
using (followupconsultantEntities dataModel = new followupconsultantEntities())
{
var myEvents = from e in dataModel.functions
select e;
foreach (var function in myEvents)
{
SelectListItem myList = new SelectListItem
{
Value = function.ID_Function.ToString(CultureInfo.InvariantCulture),
Text = function.FU_Name
};
result.Add(myList);
}
}
return result;
} }
Thanks for help
The view:
<div class="editor-field">
<%: Html.DropDownListFor(m => m.SelectedFunction,Model.Functions) %>
</div>
For information, my controller:
public ActionResult Register()
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View(new RegisterModel());
}
Start using System.Web.Mvc.SelectList.
Also consider AutoMapper.