填充mvc下拉列表的值

本文关键字:下拉列表 mvc 填充 | 更新日期: 2023-09-27 18:03:29

 @Html.DropDownListFor(x => x.Pets, new SelectList(ViewBag.Pets, "key", "value"), new { @class = "type1 newdrop" })

我是mvc开发的新手。使用上面的代码行,我得到了下拉列表,但只有2作为值。

如何将下拉列表填充为低于2的所有值,包括0?我希望所选项目为2

 ViewBag.Pets = Constants.MaxP.Where( x => x.Key == someId); // the someId is for sure one of the below key numbers

其中

  public static Dictionary<int, int>   MaxP = new Dictionary<int, int>(){
                {12, 2}, {13, 2}, {14, 2}, {15, 2}, {16, 2}, {17, 2}, {18, 2}
            };

填充mvc下拉列表的值

把你的字典变成SelectListItem的集合,如下所示:

int a = Constants.Maxp.FirstOrDefualt(x => x.Key == SomeID).Value;
List<SelectListItem> lst = new List<SelectListItem>();
for (int i = 0; i < a; i++)
{
    lst.Add(new SelectListItem(){
        Text = i.ToString(),
        Value = i.ToString()
    });
}
ViewBag.Pets = lst;

然后在你看来:

@Html.DropDownListFor(x => x.Pets, ViewBag.Pets, new { @class = "type1 newdrop" })

其中x.pets是与Key 匹配的ID

以下是我们通常如何填充dropdownlist。

例如,您为您的项目创建了一个类,以便在下拉列表中进行衰减:

public class MaxP
{
    public int Key { get; set; }
    public int Value { get; set; }
}

然后,在控制器中执行操作时,您可以像这样填充您的选择列表:

var list = new List<MaxP>();
list.Add(new MaxP { Key = 12, Value = 2 });
list.Add(new MaxP { Key = 13, Value = 2 });
list.Add(new MaxP { Key = 14, Value = 2 });
ViewBag.Pets = new SelectList(list, "Key", "Value", null);

在你看来:

@Html.DropDownListFor(x => x.Pets, (SelectList)ViewBag.Pets, new { @class = "type1 newdrop" });

请注意,下拉列表中显示的文本为"2"。如果选择了它,你将得到的值将是"键",在我们的例子中是12、13和14。

希望它是清楚的。从初学者的角度来看,这可能很复杂,但没关系,我们都去过。但我鼓励你开始做基本的和你的好去。请从基础开始学习。这里有一个很好的起点:http://www.asp.net/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part1

代码没有经过测试,但我希望你明白要点,快乐学习

var certainKey = 15;
var certainValue = 2;

key less than certainKey 的所有项目填充dropdownlist

 ViewBag.Pets = Constants.MaxP.Where( x => x.Key < certainKey);

value less than certainValue 填充dropdownlist的所有项目

 ViewBag.Pets = Constants.MaxP.Where( x => x.Value < certainValue);

key equal with certainKeyvalue less than certainValue 的项目填充dropdownlist

 ViewBag.Pets = Constants.MaxP.Where( x => x.Key == certainKey && x.Value < certainValue);

对于逻辑和功能:

  • Dictionary中,Key(id(应该是唯一的,并且Value可以重复

  • SelectList中,Value(id(应该是唯一的,并且Text可以重复

  • 最后,在dropdownlist列表中,您应该使用SelectList,然后当您为dropdownlist使用dictionary时,您应该在Dicatinary的基础上创建SelectList。您正在执行此操作,转换模式如下所示:
  • Dicatinary密钥>>>SelectList
  • Dictionary>SelectList文本

现在决定你应该在字典选择中使用什么条件来达到目标。


编辑:

Dictinary创建Selectlist,并将默认选择的值设置为Max value:

Dictionary<int,int> myDictionary = GetDictionary();
var pets=new SelectList(myDictionary, "key","value", myDictionary.Max(x => x.Key));

传递已填充的selectList以查看

ViewBag.Pets = pets;

视图中:

@{
  var myPets = ViewBag.Pets as Dictionary<int,int>;
}
@Html.DropDownListFor(x => x.Pets, myPets, new { @class = "type1 newdrop" })

现在,您只需要根据应用程序逻辑编写GetDictionary()方法代码,即可创建适当的数据字典。