Seth
Seth

Reputation: 6832

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

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?

Upvotes: 1

Views: 2744

Answers (2)

ShaneKm
ShaneKm

Reputation: 21328

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();

Upvotes: 3

jason
jason

Reputation: 2259

You could try annotating the property with:

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

Upvotes: 0

Related Questions