简体   繁体   中英

How simplify my request code?

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 .

public IEnumerable<SelectListItem> Functions { get
{
    using (followupconsultantEntities dataModel = new followupconsultantEntities())
    {
        return new SelectList(dataModel.functions.ToArray(), "ID_Function", "FU_Name");
    }
}

Also consider AutoMapper .

Try this. In this code you will not get from database data that you not need.

public IEnumerable<SelectListItem> Functions { get
{
    using (followupconsultantEntities dataModel = new followupconsultantEntities())
    {
        return new SelectList(dataModel.functions.Select(f=>
               new 
               {
                   Value = function.ID_Function.ToString(CultureInfo.InvariantCulture),
                   Text = function.FU_Name
               })
               .ToArray(), "Value", "Text");
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM