【问题标题】:Formatting dates in an MVC Dropdown在 MVC 下拉菜单中格式化日期
【发布时间】:2015-06-15 12:18:32
【问题描述】:

我的页面上有一个下拉列表:-

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

其中 seasonDates 是日期的 IList。问题是当日期显示在下拉列表中时,它们也有时间。如何格式化显示日期以便不包括时间。

【问题讨论】:

  • 你需要在 seasonDates() 函数中这样做
  • 它只是视图模型中包含日期列表的属性

标签: date model-view-controller html-select


【解决方案1】:

也许更好的方法是在你的模型中定义一个返回IEnumerable<SelectListItem>的属性(在你的模型类中):

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 =&gt; m.SelectedDate, @Model.SeasonDates, "Please Select")

如有错误请见谅,我没有打开VS来验证sytanx。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多