【发布时间】:2014-04-10 14:44:45
【问题描述】:
我是 mvc 的新手。所以我以这种方式填充下拉列表
public ActionResult New()
{
var countryQuery = (from c in db.Customers
orderby c.Country ascending
select c.Country).Distinct();
List<SelectListItem> countryList = new List<SelectListItem>();
string defaultCountry = "USA";
foreach(var item in countryQuery)
{
countryList.Add(new SelectListItem() {
Text = item,
Value = item,
Selected=(item == defaultCountry ? true : false) });
}
ViewBag.Country = countryList;
ViewBag.Country = "UK";
return View();
}
@Html.DropDownList("Country", ViewBag.Countries as List<SelectListItem>)
我想知道如何从模型中填充下拉列表并设置默认值。任何示例代码都会有很大帮助。谢谢
【问题讨论】:
-
@Html.DropDownList("Country", ViewBag.Country as List
, "DefaultValueHere") -
你应该使用 Model 而不是 ViewBag。 stackoverflow.com/questions/6807256/…
-
@DanielMelo:实际上,该参数决定了应该为“空”选项显示的名称,不是默认值。
-
从
@Html...sn-p 判断,ViewBag.Country = countryList;应为ViewBag.Countries = "UK";
标签: asp.net-mvc