在MVC下拉菜单中格式化日期 [英] Formatting dates in an MVC Dropdown
问题描述
我的页面上有一个下拉列表,如下所示:-
I have a dropdown list on my page as so: -
@Html.DropDownList("dd_dates", new SelectList(@Model.seasonDates), "Please Select")
其中seasonDates是日期的IList.问题在于,当日期显示在下拉列表中时,它们上也有时间.如何设置显示日期的格式,以便不包括时间.
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.
推荐答案
也许更好的方法是在模型中定义一个返回IEnumerable<SelectListItem>
的属性(在模型类中):
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
};
}
}
然后在视图中使用它:
@Html.DropDownListFor(m => m.SelectedDate, @Model.SeasonDates, "Please Select")
抱歉,如果有错误,我没有打开VS来验证sytanx.
Apologies if there are errors, I dont have VS open to verify the sytanx.
这篇关于在MVC下拉菜单中格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!