2016-10-01 29 views
0

视图模型无法转换lambda表达式为类型 '的IEnumerable <SelectListItem>',因为它不是委托型

public class EmployeeIndexViewModel { 
    public int selectedDepartment { get; set; } 
    public IList departments1 { get; set; } 
} 

控制器动作

List<Department> list = new List<Department>(); 
list.Add(new Department { ID = 1, Name = "D1" }); 
list.Add(new Department { ID = 2, Name = "D2" }); 
list.Add(new Department { ID = 3, Name = "D3" }); 
employeeIndexViewModel.departments1 = list; 
employeeIndexViewModel.selectedDepartment = "2"; 

查看

@Html.DropDownListFor(m => m.department, new SelectList(Model.departments1, "Id", "Name")) 

现在,编码工作正常。但我不喜欢这片

new SelectList(Model.departments1, "Id", "Name") 

我想将它添加到我的视图模型,然后只需将它绑定在我看来。 所以我改变了我的ViewModel

新视图模型

public class EmployeeIndexViewModel { 
    public int selectedDepartment { get; set; } 
    public IList departments1 { get; set; } 
    public IEnumerable<SelectListItem> departments2 { get; set; }//add this 
} 

新的控制器动作

List<Department> list = new List<Department>(); 
list.Add(new Department { ID = 1, Name = "D1" }); 
list.Add(new Department { ID = 2, Name = "D2" }); 
list.Add(new Department { ID = 3, Name = "D3" }); 
employeeIndexViewModel.departments1 = list; 
employeeIndexViewModel.selectedDepartment = "2"; 
employeeIndex2ViewModel.departments2 = new SelectList(list, "id", "name");// add this 

新观点

@Html.DropDownListFor(m => m.department, new SelectList(Model.departments1, "Id", "Name")) 
@Html.DropDownListFor(m => m.department, (SelectList)(m => m.departments2))//add this 

我得到这个错误:

Cannot convert lambda expression to type 'IEnumerable<SelectListItem>' because it is not a delegate type

+1

它只是需要更换'@ Html.DropDownListFor(M => m.department, Model.departments2)'。另请注意,model-view-controller标签用于解决该模式的问题。 ASP.NET-MVC实现有一个特定的标签。 –

回答

2

在新视图 (SelectList)(m => m.departments2)取出lambda表达式,并与Model.departments2

+0

它已经'IEnumerable ' - 没有必要投它 –

+0

感谢您的意见 – Nadeem

+0

感谢您的帮助。斯蒂芬和纳迪姆 – jinxinhelloworld

相关问题