【问题标题】:Creating a dynamic dropdown list using mvc 4使用 mvc 4 创建动态下拉列表
【发布时间】:2013-11-26 15:15:53
【问题描述】:

我正在创建一个 MVC 项目,并且我正在使用 razor 作为我的视图。我对下拉列表的感觉有点基本的问题。我有一个下拉列表,我想从之前页面中的文本框中填充它,所以我将它放入一个对象中。我正在填充列表,但它不是完全动态的。

public class FormInformation
{
    public IEnumerable<SelectListItem> ListItems { get; set; }
    public string[] SelectedItems { get; set; }
    public ServiceObject serviceObject { get; set; }
}

我这样填充选择列表:

 private SelectList CreateSelectListItems(int counter, List<string> clients)
    {
        if (counter == 1)
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                    }, "Id", "Name");
        }
        if (counter == 2)
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                        new {id = 3, Name = clients[1]},
                    }, "Id", "Name");
        }
        if (counter == 3)
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                        new {id = 3, Name = clients[1]},
                        new {id = 4, Name = clients[2]},
                    }, "Id", "Name");
        }
        else
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                        new {id = 3, Name = clients[1]},
                        new {id = 4, Name = clients[2]},
                        new {id = 5, Name = clients[3]},
                    }, "Id", "Name");
        }
    }
}

我需要它是完全动态的。这只允许四种可能性。我知道这是一件小事,我对此并不了解。所以我可能有 3 个客户,或者我可能有 7 个客户。如何在不需要计数器的情况下遍历所有客户端并添加它们?非常感谢。

【问题讨论】:

    标签: asp.net-mvc-4 razor html.dropdownlistfor selectlist selectlistitem


    【解决方案1】:

    您可以尝试使用 Linq to Objects .Select() 方法重载,在通过序列迭代时给出元素的索引:

    private SelectList CreateSelectListItems(List<string> clients)
    {
        clients.Insert(0, "");
        var items = clients.Select((el, index)=> new {id = index + 1, Name = el})
                           .ToList();
        return new SelectList(items, "Id", "Name");
    }
    

    【讨论】:

    • 太棒了!这正是我所需要的。非常感谢,这对您有很大帮助。
    猜你喜欢
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多