注意:变量名称已更改以使我的代码的目的保持匿名。
任务:
创建一个SelectList
将显示选择的内容(如果选择了任何内容),并将生成一个可供选择的列表。
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
控制器和“编辑视图”代码有问题?
我想提前感谢任何有帮助的人。