DropDown for Edit() [Razor]View, Pre-Loaded with Data from Model
Solution 1
I ended up implimenting this way, and it worked like a dream.
Controller Code:
SelectList typelist = new SelectList(context.CompanyType.ToList(), "CompanyTypeId", "Type", context.CompanyType);
ViewData["CompanyTypes"] = typelist;
View Code:
@Html.DropDownList("CompanyTypeId", (IEnumerable<SelectListItem>) ViewData["CompanyTypes"])
Solution 2
There may be bugs in this code - I haven't tested it - but what you basically want to do is:
var etId = ??? // EmployeeTypeId from your model
var employeeTypes = context.EmployeeTypes.Select(et => new SelectListItem
{
Value = et.EmployeeTypeId.ToString(),
Text = et.Type.ToString(),
Selected = et.EmployeeTypeId == etId
});
ViewData["EmployeeTypeList"] = employeeTypes.ToList();
Then in your view you can do
@Html.DropDownList("EmployeeType", ViewData["EmployeeTypeList"])
Timothy Green
After Years of Web Design and Development, I am learning ASP.NET MVC3 with C#. I can't wait to fully understand it.
Updated on June 05, 2022Comments
-
Timothy Green almost 2 years
I have the dropdowns in my Create() View working perfect.
But in the Edit() View I can't get the Data that was submited during the Create() to show up in DropDowns with the Value enterened upon Create()
I just have textboxs in place at the moment And would really like to have Data Represented in a dropdown for easy selection.
Here is one example:
Create() View - One dropdown is for EmployeeTypes, and stores selected to EmployeeTypeId
Now How do I get that to show up in the Edit() View as the same dropdown, but with Value of EmployeeId already selected?
I have a EmployeeViewModel for the Create() View
But I am just passing the model directly into the Edit() View
Should I create some kind of Employee "partial class" for the Edit() View? to handle the IEnumerable Lists?
and set:
var employeeTypes = context.EmployeeTypes.Select(et => new SelectListItem { Value = et.EmployeeTypeId.ToString(), Text = et.Type.ToString() });
Or should I pass them in as ViewData?
If so how to do you pass a List in as ViewData and get it to display as an @Html.DropDownList with the Value passed in from the @Model as the defualt value?