来自Controller我正在使用ViewBag将Batch列表传递给View,这一点运行良好。代码如下:
控制器代码:
[HttpGet]
public ActionResult RegisterForProgrammingContest()
{
List<SelectListItem> Batch = GetBatch();
ViewBag.Batch = Batch;
return View();
}
private List<SelectListItem> GetBatch()
{
List<SelectListItem>batch = new List<SelectListItem>
{
new SelectListItem {Text = "39th", Value = "39"},
new SelectListItem {Text = "40th", Value = "40"},
new SelectListItem{Text = "41st",Value = "41"}
};
return batch;
}
查看代码:
@Html.LabelFor(m => m.Batch, new {@class = "text-success"})
@Html.DropDownListFor(m => m.Batch, ViewBag.Batch as SelectList, new {@class = "form-control", @style = "width:250px"})
@Html.ValidationMessageFor(m => m.Batch)
但是当我尝试使用ViewBag传递一系列部门以及批处理列表时。我收到了一个错误。我的修改后的代码如下:
控制器代码:
[HttpGet]
public ActionResult RegisterForProgrammingContest()
{
List<SelectListItem> Batch = GetBatch();
ViewBag.Batch = Batch;
List<SelectListItem> Department = GetDepartment();
ViewBag.Department = Department;
return View();
}
private List<SelectListItem> GetBatch()
{
List<SelectListItem>batch = new List<SelectListItem>
{
new SelectListItem {Text = "39th", Value = "39"},
new SelectListItem {Text = "40th", Value = "40"},
new SelectListItem{Text = "41st",Value = "41"},
new SelectListItem{Text = "42nd",Value = "42"},
new SelectListItem {Text = "43rd", Value = "43"},
new SelectListItem {Text = "44th", Value = "44"},
new SelectListItem{Text = "45th",Value = "45"},
new SelectListItem{Text = "46th",Value = "46"}
};
return batch;
}
private List<SelectListItem> GetDepartment()
{
List<SelectListItem> department = new List<SelectListItem>
{
new SelectListItem {Text = "CSE", Value = "CSE"},
new SelectListItem {Text = "IIT", Value = "IIT"},
new SelectListItem{Text = "Others",Value = "Others"}
};
return department;
}
查看代码这是:
<div class="row">
<div class="col-md-12">
@Html.LabelFor(m => m.Batch, new {@class = "text-success"})
@Html.DropDownListFor(m => m.Batch, ViewBag.Batch as SelectList, new {@class = "form-control", @style = "width:250px"})
@Html.ValidationMessageFor(m => m.Batch)
</div>
</div>
<div class="row">
<div class="col-md-12">
@Html.LabelFor(m => m.SelectDepartment, new { @class = "text-success" })
@Html.DropDownListFor(m => m.SelectDepartment, ViewBag.Department as SelectList, new { @class = "form-control", @style = "width:250px" })
@Html.ValidationMessageFor(m => m.SelectDepartment)
</div>
</div>
我收到以下错误:
System.Web.Mvc.dll中发生了'System.InvalidOperationException'类型的异常,但未在用户代码中处理
附加信息:没有类型为“无数”的ViewData项具有“SelectDepartment”键。