如何使用ASP.NET MVC为View中的DropDownList设置默认值? [英] How to set default value for DropDownList in View using ASP.NET MVC?
问题描述
我正在尝试使用通过ViewBag传递给我的View的SelectList的数据在View中创建一个DropDownList:
I'm trying create a DropDownList in my View with data of a SelectList passed to my View using ViewBag:
ViewBag.OtherKeysList = new SelectList(list, "OtherKey");
在我的视图中,我创建一个WebGrid,其中的列表示此DropDownList,如下所示:
In my View i create a WebGrid with a column representing this DropDownList like this:
grid.Column(columnName: "OtherKey", header: "OtherKey", format: @<text>@Html.DropDownList("OtherKey", (IEnumerable<SelectListItem>)ViewBag.OtherKeysList, new { @class = "extra-class" })</text>)))
但是,此列表仅使用列表中的第一项作为其默认值.如何将此列表的另一个值设置为其默认值?
However this list just uses the first item in the list as its default value. How to set another value of this list to its default value?
更新:
当我尝试以下代码时:
public ActionResult EditMapping(int id)
{
var list = new ListWithDuplicates();
var v = (from a in dbProducts.MapperConfigs
where
a.MappingID.Equals(id)
select a
);
foreach (var item in v)
{
list.Add(item.OtherKey, item.OtherKeyType);
}
ViewBag.TotalRows = v.Count();
ViewBag.OtherKeysList = list.Select(x => new SelectListItem() { Text = x.Key, Value = x.Key, Selected = x.Key == "keyC" ? true : false });
ViewBag.MappingName = (from a in dbProducts.MappingNames
where
a.MappingID.Equals(id)
select a.Name
).First();
var data = v.ToList();
return View(data);
}
我得到以下结果:
无论如何配置:
我要实现的目标是:
Key1:具有默认值keyA的DropDownlist
Key1 : DropDownlist with default value keyA
Key2:默认值为keyB的下拉列表
Key2 : Dropdownlist with default value keyB
Key3:默认值为keyC的DropDownlist
Key3 : DropDownlist with default value keyC
Key4:默认值为keyD的下拉列表
Key4 : Dropdownlist with default value keyD
推荐答案
我假设您可以通过操作绑定到的list
中的默认 SelectListItem 来获得所需的结果.选择列表.
I assume that you can achieve your desired result by manipulating the default SelectListItem in the list
which is binded to SelectList.
var defaultItem = new SelectListItem()
{
Value = 1,
Text = "Default Item",
Selected = true
};
这篇关于如何使用ASP.NET MVC为View中的DropDownList设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!