Formatting dates in an MVC Dropdown

2019-03-04 03:23发布

问题:

I have a dropdown list on my page as so: -

@Html.DropDownList("dd_dates", new SelectList(@Model.seasonDates), "Please Select")

where seasonDates is an IList of dates. The problem is that when the dates are displayed in the dropdown they also have the time on them as well. How do I format the display date so that the time is not included.

回答1:

Maybe a better way to do this would be to define a property in your model that returns IEnumerable<SelectListItem> (in your model class):

public DateTime SelectedDate {get;set;}

public IEnumerable<SelectListItem> SeasonDates
{
    get
    {
        foreach (var item in seasonDates)
            yield return new SelectListItem() 
            { 
                Text = item.ToShortDateString(), // or apply your own formatting!
                Value = item
             };
    }
}

Then use this in the view:

@Html.DropDownListFor(m => m.SelectedDate, @Model.SeasonDates, "Please Select")

Apologies if there are errors, I dont have VS open to verify the sytanx.