0

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

任务

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

ViewBagCarShow控制器中的声明/定义

/* 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控制器和“编辑视图”代码有问题?

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

4

2 回答 2

2

试试这个我不认为你想区分列表

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


@Html.DropDownList("CompanyList", (SelectList)ViewBag.CompanyList)
于 2013-04-23T01:41:37.383 回答
0

在您看来,请使用强类型版本:

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

在您的控制器中,.Distinct()从行尾删除...如果您需要它,请以这种方式使用它:

ViewBag.CompanyList = new SelectList( db.Companies.Distinct(), "Id",  "Name", CarShow.Company.Id );
于 2013-04-23T03:00:57.360 回答