How to format the dates that appear in Html.DropDownListFor?

99封情书 提交于 2019-12-31 05:09:05

问题


I have an object:

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

In a collection in a model:

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

And I'm populating a dropdown list using Razor:

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

How can I format the dates that appear in that dropdown list?


回答1:


in your controller:

model.SelectMilk will hold a list of SelectListItems

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



回答2:


You could try annotating the property with:

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


来源:https://stackoverflow.com/questions/14606458/how-to-format-the-dates-that-appear-in-html-dropdownlistfor

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