繁体   English   中英

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

[英]How to create a DropDownList from an encapsulated property from a dynamically created ViewBag?

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

任务

创建一个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控制器和“编辑视图”代码出错了吗?

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

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

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


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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM