如何将不同的数据返回到DropDownListFor?

时间:2014-11-26 08:23:40

标签: asp.net-mvc distinct html.dropdownlistfor

我用C#应用.Net MVC结构。在控制器中,我想要不同特定列(IndustryName),并将结果返回到视图中的 Html.DropDownListFor 。但是我在视图中遇到了运行时错误:

  

System.Web.HttpException:DataBinding:' System.String'不包括   ' IndustryName'属性。

有没有人遇到这样的问题,如何解决?   非常感谢你的帮助。

控制器:

public ActionResult Create()
{
   var industrys = this._pmCustomerService.GetAll().Select (x => x.IndustryName).Distinct();
   ViewBag.Industrys = new SelectList(industrys, "IndustryName", "IndustryName", null);
   return View(); 
}

查看:

@Html.DropDownListFor(model => model.IndustryName, (SelectList)ViewBag.Industrys)

4 个答案:

答案 0 :(得分:2)

您的查询正在返回IEnumerable<string>(您只选择IndustryName子句中的.Select()属性。string不包含名为IndustryName的属性,因此您得到此错误。只需将SelectList更改为

即可
ViewBag.Industrys = new SelectList(industrys);

这会将选项值和显示文本绑定到IndustryName

的值

答案 1 :(得分:1)

您收到此错误是因为您使用错误的集合创建了SelectList。这应该是我认为的。

var industrys = this._pmCustomerService.GetAll().Select(x => new SelectListItem
                {
                    Value = x.IndustryName,
                    Text = x.IndustryName
                }).Distinct();
ViewBag.Industrys = new SelectList(industrys);
return View();  

答案 2 :(得分:1)

以下示例实现可帮助您解决问题:

var industries= this._pmCustomerService.GetAll()
                    .GroupBy(ind => new { ind.IndustryName})
                    .Select(group => new SelectListItem 
                                     { 
                                       Text = group.First().Name, 
                                       Value = group .First().Name 
                                     }
                           );
ViewBag.Industries= industries;

你可以找到更多关于'GroupBy&amp;选择“接近而不是使用linq的Distinct(),here

查看

@Html.DropDownList("ddlIndustries",(@ViewBag.Industries) as IEnumerable<SelectListItem>)

如果您想使用DropDownListFor helper,请修改视图代码,如下所示:

@{
    var industries = ViewBag.Industriesas IEnumerable<SelectListItem>;
}
@Html.DropDownListFor(m=> industries , industries )

答案 3 :(得分:0)

您只选择显然属于String类型的IndustryName,使用MoreLinq by Jon Skeet中的DistinctBy(),这里是引用SO post

public ActionResult Create()
{
   var industrys = this._pmCustomerService.GetAll().DistinctBy(x => x.IndustryName); 
   ViewBag.Industrys = new SelectList(industrys, "IndustryName", "IndustryName", null);
   return View(); 
}