Good Day everyone. I have next question.
I have Edit form with few DropDownList controls on it. I need to bind selected value in DropDownListFor based upon data which I have in my db.
What I have is next:
Model:
Supplier
public class Supplier{
public int SupplierID { get; set; }
public string CompanyName { get; set; }
}
Delviery
public class Delivery{
public int DeliveryID { get; set; }
public string DeliveryCode { get; set; }
public int SupplierID { get; set; }
public virtual Supplier Supplier { get; set; }
}
ViewModel for Delivery Edit Screen:
public class DeliveryEditViewModel{
public int DeliveryID { get; set; }
public string SelectedCompanyName { get; set; }
public IEnumerable<SelectListItem> Suppliers { get; set; }
}
View:
<dd>
@Html.DropDownListFor(x => x.SelectedCompanyName, new SelectList(Model.Suppliers, "Value", "Text"), htmlAttributes: new { @class = "form-control" })
</dd>
Controller:
// GET: Deliveries/Edit
public ActionResult Edit(int? id){
db.Configuration.ProxyCreationEnabled = false;
DeliveryEditViewModel model = db.Deliveries.Include(s => s.Supplier).Include(a => a.Auction).Include(q => q.Quality).Include(t => t.BulbType)
.Where(d => d.DeliveryID == id)
.Select(x => new DeliveryEditViewModel{
DeliveryID = x.DeliveryID,
SelectedCompanyName = x.Supplier.CompanyName
})
.Single();
model.Suppliers = db.Suppliers.Where(s => s.IsActive == true).Select(x => new SelectListItem{
Value = x.SupplierID.ToString(),
Text = x.CompanyName
});
return View(model);
}
Problem is that I can't setup selected value in DropDownListFor based upon data which I already have inside my database.Instead I have DropDown control with first element active always. I already tried solutoin from Html.DropdownListFor selected value not being set but still I have first value selected instead of real one.
Hours of researching and already bold hair makes me to stop and ask for a help. Please help me to figure out how it could be possible.
Thank you so much.