如何从动态创建的ViewBag中的封装属性创建DropDownList?

时间:2013-04-23 01:18:40

标签: c# asp.net-mvc-4 viewdata viewbag

注意:变量名称已更改,以保持我的代码的目的是匿名的。

任务

创建一个SelectList,显示所选内容(如果选择了任何内容),并生成一个可供选择的列表。

{p> ViewBag CarShow控制器中的声明/定义

/* db.Companies is DataContext (Entities), 
*  CarShow.Company.Id is a ViewModel (Company is encapsulated under CarShow) */
ViewBag.CompanyList = new SelectList( db.Companies,       //Constructor
                                      "Id",               //Property Name
                                      "Name",             //Text to display each item
                                      CarShow.Company.Id  //Value of the initially selected item
                                      ).Distinct();

我在“编辑视图”中尝试了以下代码,生成SelectList及其错误消息:

/* <-- The ViewData item that has the key 'Company.Id' is of 
    type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. --> */
@Html.DropDownListFor( model => model.Company.Id,
                      (IEnumerable<SelectListItem>)ViewBag.CompanyList )

/* <!-- Compilation Error --> */
@Html.DropDownList( (IEnumerable<SelectListItem>)ViewData.Id,
                    (IEnumerable<SelectListItem>)ViewData.Name )

/* <!-- The ViewData item that has the key 'Id' is of type 'System.Int32' 
     but must be of type'IEnumerable<SelectListItem>'. --> */
@Html.DropDownList( "Id", 
                    (IEnumerable<SelectListItem>)ViewData["Name"], 
                     new { id = "Id" })

/* <!-- Cannot apply indexing with [] to an 
     expression of type 'System.Dynamic.DynamicObject' --> */
@Html.DropDownList("Id", (IEnumerable<SelectListItem>)ViewBag["Name"])

我的方法是否正确,我的“修改视图”代码或我的CarShow控制器和“编辑视图”代码出错了?

我想提前感谢任何有帮助的人。

2 个答案:

答案 0 :(得分:2)

尝试这个我认为你不想区分清单

ViewBag.CompanyList = new SelectList( db.Companies.Distinct().ToList(),      
                                      "Id",             
                                      "Name",             
                                      CarShow.Company.Id);


@Html.DropDownList("CompanyList", (SelectList)ViewBag.CompanyList)

答案 1 :(得分:0)

在您的视图中使用强类型版本:

@Html.DropDownListFor( model => model.Company.Id, (SelectList)ViewBag.CompanyList )

在你的控制器中,从行尾删除.Distinct() ...如果需要,可以这样使用:

ViewBag.CompanyList = new SelectList( db.Companies.Distinct(), "Id",  "Name", CarShow.Company.Id );