您好我试图将下拉列表分组
控制器中的
public ActionResult Index()
{
IEnumerable<GroupedSelectListItem> item;
item = new List<GroupedSelectListItem> {
new GroupedSelectListItem() { Value = "volvo", Text = "Volvo", GroupName = "Swedish Cars", GroupKey = "1", Disabled = true },
new GroupedSelectListItem() { Value = "saab", Text = "Saab",GroupName = "Swedish Cars", GroupKey = "1" },
new GroupedSelectListItem() { Value = "mercedes", Text = "Mercedes", GroupName = "German Cars", GroupKey = "2" },
new GroupedSelectListItem() { Value = "audi", Text = "Audi", GroupName = "German Cars", GroupKey = "2",Selected = true }};
ViewBag.item = item;
return View();
}
并在视图中
<div class="form-group">
<label for="class_id" class="col-sm-2 control-label">Classe</label>
<div class="col-sm-10">
@Html.DropDownGroupList("Cars", ViewBag.item, "-- Select Car --", new Dictionary<string, object>() { { "data-val", "true" }, { "data-val-required", "The Car field is required." } })
</div
我正在尝试使用viewbag将IEnumerable传递给视图 但它不起作用 我是.net编程新手,谢谢你
答案 0 :(得分:0)
简单地添加模型并像这样使用它
Index.cshtml
@model IList<GroupedSelectListItem>
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
@Html.DropDownGroupList("Cars",Model, "-- Select Car --", new Dictionary<string, object>() { { "data-val", "true" }, { "data-val-required", "The Car field is required." } })
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
var item = new List<GroupedSelectListItem> {
new GroupedSelectListItem() { Value = "volvo", Text = "Volvo", GroupName = "Swedish Cars", GroupKey = "1", Disabled = true },
new GroupedSelectListItem() { Value = "saab", Text = "Saab",GroupName = "Swedish Cars", GroupKey = "1" },
new GroupedSelectListItem() { Value = "mercedes", Text = "Mercedes", GroupName = "German Cars", GroupKey = "2" },
new GroupedSelectListItem() { Value = "audi", Text = "Audi", GroupName = "German Cars", GroupKey = "2",Selected = true }};
return View(item);
}
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
return View();
}
}