如何在ViewBag()的帮助下填充下拉列表? [英] How to populate the Drop Down List with the help of ViewBag()?
问题描述
你好,
我不知道我的代码有什么问题。以下是代码类,并获取错误 ArgumentNullException :
我正在使用数据库第一种方法。
这是我的模型类:
Hello,
I do not know what is wrong in my code. following are the code classes respectively, and getting the error ArgumentNullException :
I am using the DB first approach.
Here is my model class:
public partial class Employee
{
public int EmployeeID { get; set; }
public Nullable<int> EmployeeTypeID { get; set; }
public int DepartmentID { get; set; }
public int GradeID { get; set; }
public virtual ICollection<BillingLinkedPersonnel> BillingLinkedPersonnels { get; set; }
public virtual Department Department { get; set; }
public virtual EmployeeType EmployeeType { get; set; }
public virtual ICollection<EmployeeDetail> EmployeeDetails { get; set; }
public virtual ICollection<EmployeeEducationDetail> EmployeeEducationDetails { get; set; }
public virtual ICollection<EmployeeLeave> EmployeeLeaves { get; set; }
public virtual Grade Grade { get; set; }
}
现在这是我的控制器类 ViewBag 对象方法:
Now here is my controller class ViewBag object method:
ViewBag.EmployeeTypeName = from EmployeeType in employee.EmployeeType.Name select new SelectListItem() { Text = employee.EmployeeType.Name, Value = employee.EmployeeType.EmployeeTypeID.ToString()};
现在这里是我的视图 DropDownListFor():
Now here is my view DropDownListFor():
@Html.DropDownListFor(m => m.EmployeeType.Name,(IEnumerable<SelectListItem>)ViewBag.EmployeeTypeName, "select city")
任何人都可以告诉我这有什么问题吗?
谢谢
Can any one tell me what is wrong with this?
Thanks
推荐答案
再看一个条件
see with one more condition
@if(ViewBag.EmployeeTypeName !=null){
@Html.DropDownListFor(m => m.EmployeeType.Name,(IEnumerable<SelectListItem>)ViewBag.EmployeeTypeName, "select city")
}
使用ToList()对于viewbag对象,因为它需要可枚举的列表
make a to use ToList() for viewbag object because it needs enumerable list
ViewBag.EmployeeTypeName = new SelectList(employee.EmployeeType.ToList(), "EmployeeTypeID", "Name", "EmployeeTypeID");
;
Controller`s Create()
Controller`s Create()
List<SelectListItem> employeeListItems = new List<SelectListItem>();
foreach (var item in _entities.Employees.ToList())
{
employeeListItems.Add(new SelectListItem() { Text = item.FirstName + " " + item.LastName, Value = item.EmployeeID.ToString() });
}
ViewBag.EmployeeList = employeeListItems;
比视图
Than the in the view
@Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewBag.EmployeeList })
感谢Sankarsan先生帮助最高级别。
Thank you Sankarsan Sir for helping at an highest level.
这篇关于如何在ViewBag()的帮助下填充下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!