Note: Variables names were changed to keep my code's purpose anonymous.
Task:
Create a SelectList
that will show what was chosen (if anything was chosen), and will generate a list to choose from.
ViewBag
Declaration / Definition in the CarShow
Controller:
/* 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();
I have tried the following code in my "Edit View" to generate the SelectList
with its error message:
/* <-- 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"])
Is my approach right and something is wrong in my "Edit View" code or my CarShow
Controller and "Edit View" code wrong?
I would like to thank you in advance to anyone that helps.