SelectListItem List's "Selected" item not being set in view

24 views Asked by At

I need to generate a list of years to select from, with the current year being selected by default. Nothing complex. I'm setting the first item in the list as "selected". The list shows the first item has Selected = true when stepping through the code, but when the view loads, the current year is not selected, and the attribute isn't added to the HTML. Here's the code to generate the year list:

public int CurrentYear { get { return DateTime.Now.Year; } }
public int FiscalYear { get; set; }
public List<SelectListItem> FiscalYearList 
{ 
    get 
    {
        var yearList = new List<SelectListItem>();

        for (var i = 0; i <= 5; i++)
        {
            yearList.Add(new SelectListItem 
            { 
                Text = (CurrentYear - i).ToString(), 
                Value = (CurrentYear - i).ToString(), 
                Selected = (i == 0) 
            });
        }

            return yearList;
        } 
    }
}

And here is the cshtml code:

<select id="FiscalYearList" asp-for="FiscalYear" asp-items="Model.FiscalYearList" class="form-control">
    <option>---Select---</option>
</select>
1

There are 1 answers

0
Irish On

The answer to this was unintuitive. I set the "default" selected year as the value of "asp-for", and got rid of the manual setting of the selected item value.

public int FiscalYear { get { return DateTime.Now.Year; } }
public List<SelectListItem> FiscalYearList 
{ 
    get 
    {
        var yearList = new List<SelectListItem>();

        for (var i = 0; i <= 5; i++)
        {
            yearList.Add(new SelectListItem 
            { 
                Text = (FiscalYear - i).ToString(), 
                Value = (FiscalYear - i).ToString()
            });
        }

        return yearList;
    } 
}



<select id="FiscalYearList" asp-for="FiscalYear" asp-items="Model.FiscalYearList" class="form-control">
    <option>---Select---</option>
</select>

This set the value of "FiscalYear" as the selected item in the drop-down. So setting this value explicitly in code was ignored, but it works like this. Strange.