I have this code:
@Html.DropDownList("ddlCouponsAppointment",
Model.Coupons.Select(a => new SelectListItem {
Text = a.Name,
Value = a.CouponId.ToString(),
Selected = (a.CouponId == Model.CouponForAppointmentReminders.CouponId)
}),
"None",
new { @class = "normalcell" })
This has worked for ages. Now, it throws an error, which a google tells me is because I am not allowed to call ToString on an entity that is being mapped to a class ( this class has not changed, so I am at a loss how it worked before ). So I added a property called CouponIdStr, which is a string representation. This does not work ( blows up b/c the property is not mapped to the DB ). I tried making value equal string.Empty + a.CouponId ( as C# would concatenate that as a string ). It blows up.
So I tried this:
@Html.DropDownList("ddlCouponsAppointment",
new SelectList(Model.Coupons,
"Name",
"CouponId",
Model.CouponForAppointmentReminders.CouponId),
"None",
new { @class = "normalcell" })
This works, but does not show the selected item. Does anyone have any suggestions ?
step 1. Create a ViewModel that has the selected value
step 2. In that ViewModel have the list of items you want in the select list
step 3. In your view, use the DisplayFor method
There you have it, when the dropdown renders, it will have the selected value selected!
Good Luck!