如何格式化出现在Html.DropDownListFor的日期?(How to format the

2019-08-16 15:35发布

我有一个对象:

class Milk {
    public DateTime ExpirationDate {get;set;}
    ...
}

在模型中的集合:

class GroceryModel {
    public IList<Milk> Milks {get;set;}
    public Milk SelectedMilk {get;set;}
}

而且我用填充剃刀的下拉列表:

@Html.DropDownListFor(m => m.ExpirationDate, Model.Milks, ...);

我怎样才能格式化出现在下拉列表中的日期?

Answer 1:

在你的控制器:

model.SelectMilk将举行SelectListItems名单

        model.SelectMilk =
            Milks.Select(
                item =>
                new SelectListItem
                    {
                        Selected = false, 
                        Value = item.ExpirationDate , 
                        Text = datetime.ToShortDateString() //or whatever format you need
                    }).ToList();


Answer 2:

你可以尝试用注释的属性:

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]


文章来源: How to format the dates that appear in Html.DropDownListFor?