C # MVC 5 - Generating select list for dates doesn't work

I am trying to create a SelectList for Dates formatted MMMM/yyyy

in the TEXT property and yyyy-MM-dd

in the VALUE property.

Everything works well, but when I use this SelectList in edit option

and I need to fill out the form to edit, the SELECTED property doesn't work and I don't know why ...

My list creation method:

public SelectList GetSLDate(DateTime _dateLimit, DateTime? _selected = null)
{
    var list = new List<SelectItemList>();
    var date = new DateTime(2015, 1, 1);

    int month = Math.Abs(12 * (_dateLimit.Year - date.Year) + (_dateLimit.Month - date.Month + 1));

    for (int m = (month - 1); m >= 0; m--)
    {
        var dateRef = date.AddMonths(m);

        list.Add(
            new SelectListItem
            {
                Text = dateRef.ToString("MMMM/yyyy"),
                Value = dateRef.ToString("yyyy-MM-dd")
            }
        );

        return new SelectList(list, "Value", "Text", ((_selected == null) ? null : (((DateTime)_selected).ToString("yyyy-MM-dd"))));
    }
}

      

+3


source to share


1 answer


When you create your SelectListItem try setting the property Selected

:



        new SelectListItem
        {
            Text = dateRef.ToString("MMMM/yyyy"),
            Value = dateRef.ToString("yyyy-MM-dd"),
            Selected = _selected == dateRef
        }

      

0


source







All Articles