在MVC下拉菜单中格式化日期 [英] Formatting dates in an MVC Dropdown

查看:85
本文介绍了在MVC下拉菜单中格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一个下拉列表,如下所示:-

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆