问题
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