gpt4 book ai didi

c# - 如何将 SelectListItem 转换为 SelectList 并分配给 mvc 下拉列表

转载 作者:行者123 更新时间:2023-12-01 22:18:10 25 4
gpt4 key购买 nike

下面是选择列表项的集合:我想将此选择项转换为 SelectList 并将其分配给 mvc dropdownlist。

List<SelectListItem>     Genderitems     =    new List<SelectListItem>();
Genderitems.Add(new SelectListItem() { Text = "Female", Value = "Female" });
Genderitems.Add(new SelectListItem() { Text = "Male", Value = "Male" });
Genderitems.Add(new SelectListItem() { Text = "Other Gender", Value = "Other Gender" });
Genderitems.Add(new SelectListItem() { Text = "Unspecified or Unknown", Value = "Unspecified or Unknown" });

最佳答案

也许你正在寻找这个

List<SelectListItem>     Genderitems     =    new List<SelectListItem>();
Genderitems.Add(new SelectListItem() { Text = "Female", Value = "Female" });
Genderitems.Add(new SelectListItem() { Text = "Male", Value = "Male" });
Genderitems.Add(new SelectListItem() { Text = "Other Gender", Value = "Other Gender" });
Genderitems.Add(new SelectListItem() { Text = "Unspecified or Unknown", Value = "Unspecified or Unknown" });
SelectList sl = new SelectList(Genderitems, "Value", "Text");
ViewBag.GenderList = sl;

在你看来如果您不想将选择严格限制在模型上

@Html.DropDownList("drpGender", ViewBag.GenderList as SelectList, "Select Gender", new { id = "drpGender"})

在其他情况下你可以

@Html.DropDownListFor(x=>x.Gender, ViewBag.GenderList as SelectList, " ", new { id = "drpGender"})

关于c# - 如何将 SelectListItem 转换为 SelectList 并分配给 mvc 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42549070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com