简体   繁体   English

ASP.NET MVC 3列表 <T> 到IEnumerable <SelectListItem>

[英]ASP.NET MVC 3 List<T> to IEnumerable<SelectListItem>

I'm not currently happy with the way that my DropDownListFor() objects are populated. 我目前不满意填充DropDownListFor()对象的方式。 I'm attempting to find as generic way of populating IEnumerable as possible. 我试图找到尽可能填充IEnumerable的通用方法。 This is what I have so far. 这就是我到目前为止所拥有的。

Helper: 帮手:

public static List<SelectListItem> ToSelectList(IDictionary<string,string> dictionaryItems, string selectedValue, string noSelection, bool search = false)
    {
        List<SelectListItem> items = new List<SelectListItem>();

        if (search)
        {
            items.Add(new SelectListItem { Selected = true, Value = "-1", Text = string.Format("-- {0} --", noSelection) });
        }

        foreach (var item in dictionaryItems)
        {
            items.Add(new SelectListItem
            {
                Text = item.Key,
                Value = item.Value,
                Selected = selectedValue == item.Value ? true : false
            });
        }

        return items
            .OrderBy(l => l.Text)
            .ToList();
    }

Controller: 控制器:

[HttpGet]
    public ActionResult Index()
    {
        var model = new CreateModel();

        var parentOrganisations = _orgs.FindBy(o => o.OwningOrganisationID == Globals.OrganisationID || o.ID == Globals.OrganisationID)
            .OrderBy(o => o.OrganisationName);

        Dictionary<string, string> items = new Dictionary<string, string>();

        foreach (var item in parentOrganisations)
        {
            items.Add(item.OrganisationName, item.ID.ToString());
        }

        model.Organisations = SelectLists.ToSelectList(items, "-1", "-- None -- ", true);

        return View(model);
    }

View: 视图:

<div class="control-group">
        <label class="control-label">Parent Organisation</label>
        <div class="controls">
            @Html.DropDownListFor(m => m.ParentOrganisationID, Model.Organisations, new { @class = "input-xlarge"})
            <p class="help-block">Select a parent organisation to create a branch</p>
        </div>
    </div>

There seems to be A LOT of repetitive code in the controller. 控制器中似乎有很多重复的代码。 It takes a generic list, add's the Value and Text to a Dictionary and then uses that as input for a helper which builds up the select list to send as part of the model. 它需要一个通用列表,将值和文本添加到字典中,然后将其用作帮助程序的输入,该帮助程序构建选择列表以作为模型的一部分发送。

Does anyone have any better ways to achieve this? 有没有人有更好的方法来实现这一目标? I hate having bloat in my controller, and when I get several drop downs on a form this is exactly what will happen in this instance. 我讨厌在我的控制器中臃肿,当我在表单上得到几个下拉时,这正是在这个实例中会发生的事情。

Thanks, 谢谢,

EDIT - Thanks to Kenneth's helper method, I've now consolidated the whole thing into one call in the controller: 编辑 - 感谢Kenneth的帮助方法,我现在将整个事情整合到控制器中的一个调用中:

            model.Organisations = _orgs.FindBy(o => o.OwningOrganisationID == Globals.OrganisationID || o.ID == Globals.OrganisationID)
            .OrderBy(o => o.OrganisationName)
            .ToList()
            .ToSelectList(org => org.OrganisationName, org => org.ID.ToString(), "-1", "None", true);

You could provide callbacks that obtain the key and the value and then use those. 您可以提供获取密钥和值的回调,然后使用它们。 Apart from that you can create it as an extension method: 除此之外,您可以将其创建为扩展方法:

Extension method: 扩展方法:

public static List<SelectListItem> ToSelectList<T>(this List<T> Items, Func<T, string> getKey, Func<T, string> getValue, string selectedValue, string noSelection, bool search = false)
    {
        List<SelectListItem> items = new List<SelectListItem>();

        if (search)
        {
            items.Add(new SelectListItem { Selected = true, Value = "-1", Text = string.Format("-- {0} --", noSelection) });
        }

        foreach (var item in Items)
        {
            items.Add(new SelectListItem
            {
                Text = getKey(item),
                Value = getValue(item),
                Selected = selectedValue == getValue(item) ? true : false
            });
        }

        return items
            .OrderBy(l => l.Text)
            .ToList();
    }

Usage: 用法:

List<Org>() parentOrganisations = // fetch here
model.Organisations = parentOrganisations.ToSelectList(org => org.ID.ToString(), 
                                                       org => org.OrganisationName,
                                                       "-1", 
                                                       "-- None -- ", 
                                                       true);

Note: I typed this in the SO-editor, so you might have some syntax errors (they should be easy to solve though). 注意:我在SO编辑器中键入了这个,因此您可能会遇到一些语法错误(尽管它们应该很容易解决)。

You can do in controller only like this: - 您只能在控制器中执行此操作: -

List<SelectListItem> dropdownItems = parentOrganisations
    .Select(item => new SelectListItem
    {
        Value = item.ID.ToString(),
        Text = item.OrganisationName,
        Selected = "-1" == item.ID.ToString() ? true : false
    })
    .ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IEnumerable <SelectListItem> ASP.NET MVC 5中的简单成员资格错误 - IEnumerable<SelectListItem> error in Simple Membership in ASP.NET MVC 5 MVC asp.net否IEnumerable类型的ViewData项<SelectListItem> - MVC asp.net No ViewData item of type IEnumerable<SelectListItem> ASP.NET MVC - 下拉列表 - 没有类型为&#39;IEnumerable&#39;的ViewData项 <SelectListItem> “ - ASP.NET MVC - Dropdown - There is no ViewData item of type 'IEnumerable<SelectListItem>' ASP.NET MVC - HTML 错误“没有 IEnumerable 类型的 ViewData<selectlistitem> ”</selectlistitem> - ASP.NET MVC - HTML Error “No ViewData of Type IEnumerable<SelectListItem>” ASP.NET MVC:所选值不适用于列表<selectlistitem></selectlistitem> - ASP.NET MVC : selected value not working on a List<SelectListItem> 具有下拉列表的Asp.Net MVC和SelectListItem协助 - Asp.Net MVC with Drop Down List, and SelectListItem Assistance 将通用 IDictionary 转换为 ASP.NET MVC IEnumerable<selectlistitem> : 选择 Selected 项目</selectlistitem> - Converting an generic IDictionary to an ASP.NET MVC IEnumerable<SelectListItem>: choosing the Selected item ASP.NET Core MVC - 无效的操作异常没有 Ienumerable 类型的视图数据<SelectListItem> - ASP.NET Core MVC - Invalid Operation Exception There is no viewdata of type Ienumerable<SelectListItem> 获取错误“ IEnumerable” <SelectListItem> &#39;在asp.net mvc中创建空白列表框时 - Getting error 'IEnumerable<SelectListItem>' while creating blank listbox in asp.net mvc 如何修复&#39;没有&#39;IEnumerable类型的ViewData项 <SelectListItem> &#39;那里有&#39;UserID_TO&#39;键。&#39; 在asp.net mvc中 - How to fix 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'UserID_TO'.' in asp.net mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM