Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDown for Edit() [Razor]View, Pre-Loaded with Data from Model

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?

like image 811
Timothy Green Avatar asked Dec 07 '25 04:12

Timothy Green


2 Answers

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"])
like image 69
Timothy Green Avatar answered Dec 09 '25 00:12

Timothy Green


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"])
like image 32
Andrew Cooper Avatar answered Dec 09 '25 00:12

Andrew Cooper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!