从 Viewbag Dropdown 访问数据
Access data from Viewbag Dropdown
我正在从下拉列表中获取值到控制器,但是当它返回到查看时 returns Null
视图的屏幕截图:-
控制器屏幕截图:-
public ActionResult Index(int departmentID)
{
ViewBag.dropdowndetail = null;
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.ToList().FirstOrDefault(x=>x.depId==departmentID);
return View(emp);
}
}
错误:
我做对了
我的 viewbag 在 Post 方法中没有得到任何值,所以为什么在 View 中它得到空异常
我在 Post 方法中调用我的 viewbag 并给它赋值。
用这个更改以下代码。
public ActionResult Index(int departmentID)
{
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.Where(x=>x.depId==departmentID).ToList();
ViewBag.dropdowndetail = db.departments.Distinct().ToList();
return View(emp);
}
}
您可以在控制器中使用键值方法
ViewBag.dropdowndetail = db.departments.Distinct().Select(x => new KeyValuePair<int, string>(x.depid, x.DepartmentName));
并在 View 中像这样使用 ViewBag
@Html.DropDownListFor(model => model.depid, new SelectList((IEnumerable<KeyValuePair<int, string>>)ViewBag.dropdowndetail , "key", "value"), "--Select Departments--")
我正在从下拉列表中获取值到控制器,但是当它返回到查看时 returns Null
视图的屏幕截图:-
控制器屏幕截图:-
public ActionResult Index(int departmentID)
{
ViewBag.dropdowndetail = null;
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.ToList().FirstOrDefault(x=>x.depId==departmentID);
return View(emp);
}
}
错误:
我做对了 我的 viewbag 在 Post 方法中没有得到任何值,所以为什么在 View 中它得到空异常 我在 Post 方法中调用我的 viewbag 并给它赋值。 用这个更改以下代码。
public ActionResult Index(int departmentID)
{
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.Where(x=>x.depId==departmentID).ToList();
ViewBag.dropdowndetail = db.departments.Distinct().ToList();
return View(emp);
}
}
您可以在控制器中使用键值方法
ViewBag.dropdowndetail = db.departments.Distinct().Select(x => new KeyValuePair<int, string>(x.depid, x.DepartmentName));
并在 View 中像这样使用 ViewBag
@Html.DropDownListFor(model => model.depid, new SelectList((IEnumerable<KeyValuePair<int, string>>)ViewBag.dropdowndetail , "key", "value"), "--Select Departments--")