2012-09-22 59 views
0

我的应用程序是asp.net MVC,试图将Telerik MVC Combobox绑定到模型。 这里是模型:将Telerik MVC Combobox绑定到模型

public class Person 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public bool DisplayBold { get; set; } 
     public string Value 
     { 
      get 
      { 
       return string.Format("{0}|{1}", this.Id, this.DisplayBold.ToString()); 
      } 
     } 
    } 

在控制器:

var people = new List<Person>(); 
     people.Add(new Person { Id = 1, Name = "John Doe", DisplayBold = true }); 
     people.Add(new Person { Id = 2, Name = "Jayne Doe", DisplayBold = false }); 
     ViewData["people"] = people; 
     return View(); 

我得到的值。

在视图:

<%= Html.Telerik().ComboBox() 
     .Name("ComboBox") 
      .BindTo((IEnumerable<SelectListItem>)ViewData["people"]) 
%> 

我得到follwing错误:

Unable to cast object of type 'System.Collections.Generic.List`1[caseprog.Models.Person]' to type 'System.Collections.Generic.IEnumerable`1[System.Web.Mvc.SelectListItem]'. 

我会感激你的建议。提前致谢。

回答

1

您不能仅将人员列表投射到SelectListItemIEnumerable。他们是两回事。

相反,您需要将列表转换为列表SelectListItem。你可以做,在许多方面,但这个应该工作:

.BindTo(new SelectList((IEnumerable<Person>)ViewData["people"], "Id", "Name")) 
+0

谢谢,我得到这个错误:CS1502:为“System.Web.Mvc.SelectList.SelectList的最佳重载的方法匹配(系统.Collections.IEnumerable,string,string)'有一些无效的参数 – hncl

+0

@ user373721您需要将ViewData转换为IEnumerable

+0

谢谢,抱歉,但我没那么有经验。我添加了.BindTo(新的SelectList(IEnumerable < Person > ViewData [“people”],“Id”,“Name”))。然后得到这个错误:'System.Collections.IEnumerable'是一个'类型',但使用像'变量' – hncl