0

I am trying to bind an IList property to a DropDownListFor(). The list is shown, the data from the dropdown is posted to the database successfully, however it does not show when the page is loaded again. The correct option is not selected based on the value of ClubTeamID. The default value (--) is always selected. The rest of the inputs, buttons and checkboxes in the page work fine in saving and reloading. Is there something else i am missing?

My View (Relevant Code):

@model IList<SolidarityContract>
...
@if (Model != null)
{
    for (var i = 0; i < Model.Count; i++)
    {
    ...

        <td>@Html.DropDownListFor(model => Model[i].ClubTeamID,Model[i].TeamsList, "--", htmlAttributes: new { @class = "form-control" })</td>
        <td>@Html.EditorFor(model => Model[i].Club, new { htmlAttributes = new { @class = "form-control input-sm" } })</td>
    ...
    }
}

My Class (Relevant Properties):

public class SolidarityContract{

    public SolidarityContract()
    {
        TeamsList = SelectLists.TeamsGet();
    }

    public SelectList TeamsList { get; set; }
    public Nullable<long> ClubTeamID { get; set; }
    ...

}

The SelectList:

public static  SelectList TeamsGet()
    {
        using (var db = new OlympiacosPlayerMSDBEntities())
        {

            IEnumerable<CustomSelectList> cpd = (from comp in db.Team
                                                 where comp.IsDeleted == false
                                                 select new CustomSelectList 
                                                 { ID = comp.ID.ToString(), 
                                                     Description = (comp.TeamCategoryID==1?"ΠΕΛ: ":"ΠΡΟ: ") +comp.Name }).ToList<CustomSelectList>().OrderBy(c => c.Description);
            return new SelectList(cpd, "ID", "Description");
        }
    }
Georgia Kalyva
  • 737
  • 2
  • 9
  • 23
  • Do you mean that the correct option is not selected based on the value of `ClubTeamID` (and the first option is always selected)? –  Mar 22 '17 at 10:16
  • Yes exactly what i mean. – Georgia Kalyva Mar 22 '17 at 10:17
  • The `EditorTemplate` option in the dupe is best, but you could modify your method to `public static SelectList TeamsGet(int selected) { ..... return new SelectList(cpd, "ID", "Description", selected); }` so that you create a new `SelectList` for each `SolidarityContract` in the collection (passing it the `ClubTeamID`) –  Mar 22 '17 at 10:21
  • Yes i am trying it now. Thank you. – Georgia Kalyva Mar 22 '17 at 10:23
  • Tried the second option and it worked!! – Georgia Kalyva Mar 22 '17 at 10:29

0 Answers0