I need to bind a variable number of dropdownlists, how do I achieve this?
In my project, until now I have only had to deal with binding to a known number of dropdown lists. To do this I have simply done the below:
viewModel
//for staff ddl
public List<Staff> Staff { get; set;
public int? SelectedStaffId { get; set; }
public IEnumerable<System.Web.Mvc.SelectListItem> StaffItems
{
get { return new System.Web.Mvc.SelectList(Staff, "StaffID", "FirstName"); }
}//end
view
@Html.DropDownListFor(m => m.SelectedStaffId, Model.StaffItems, "--Who is taking appointment--", new { @class = "form-control", @id = "ddlValuer" })
Now I want to bind a variable number of dropdownlists. I expected to achieve this would be a simple loop as below: (BUT THIS DOESN'T WORK)
ViewModel
//for offerState ddl
public List<OfferState> OfferStates { get; set; }
public int? SelectedOfferStateId { get; set; }
public IEnumerable<System.Web.Mvc.SelectListItem> OfferStateItems
{
get { return new System.Web.Mvc.SelectList(OfferStates, "OfferStateID", "Description"); }
}//end
View
for (var i = 0; i < Model.Offers.Count; i++)
{
<div class="row">
<div class="col-lg-4">@Html.TextBoxFor(m => Model.Offers[i].Offer1, null, new { @class = "form-control", @disabled = "disabled" })</div>
<div class="col-lg-8">@Html.DropDownListFor(m => Model.Offers[i].OfferStateID, Model.OfferStateItems, "--State--", new { @class = "form-control" })</div>
</div>
}
The items are never selected, --state-- (the default text), is always displayed. I have stepped through the code and can see there are three items with an OfferStateID.
Why is the default value always selected? Is there a better way?