Formatting dates in an MVC Dropdown

与世无争的帅哥 提交于 2019-12-02 17:21:20

问题


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.



来源:https://stackoverflow.com/questions/30845005/formatting-dates-in-an-mvc-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!