0

我使用这部分代码从我的数据库中获取信息,使用实体框架,并将所有信息添加到 IEnumerable 属性中,最后用于显示 DropDownListFor。我需要多次使用这种代码,所以我想让它在一开始就变得最强大。

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;
    } }

感谢帮助

风景:

<div class="editor-field">
<%: Html.DropDownListFor(m => m.SelectedFunction,Model.Functions) %>
</div>

有关信息,我的控制器:

public ActionResult Register()
    {
        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        return View(new RegisterModel());
    }
4

2 回答 2

1

开始使用System.Web.Mvc.SelectList

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

还要考虑AutoMapper

于 2012-09-06T09:25:41.723 回答
1

试试这个。在此代码中,您不会从不需要的数据库数据中获取。

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");
   }

}

于 2012-09-06T10:09:01.137 回答