@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}
};
把你的字典变成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 certainKey
和value 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()
方法代码,即可创建适当的数据字典。