I have a drop down that only needs to show Month/Day/Year, without time. Its bound to a IEnumerable<DateTime> supplied by the Model. With default approach a long date is shown:
@Html.DropDownList("SelectedDate", new SelectList(Model.Dates, Model.SelectedDate));
producing '6/24/2013 12:00:00 AM' for textfield of each list item in dropdown.
How can I show a short date for the text field like so:
'6/24/2013'
I would like to stick to DateTime struct for the model Data, but i guess, i could generate a custom list of objects with custom properties and run the following:
@Html.DropDownList("SelectedDate", new SelectList(Model.DisplayDates, "Value", "ShortDate", Model.SelectedDate));
But maybe there is a more elegant solution?
Make a copy, iterate through it, change the dates to a better fit
@{
List<string> shortDates = new List<string>();
for (var i = 0; i < Model.Dates.Count; i++)
{
shortDates.Add(Model.Dates.ElementAt(i).ToShortDateString());
}
}
Use the copy
@Html.DropDownList("SelectedDate", new SelectList(shortDates, Model.SelectedDate));
Basically, this is the only ugly solution I find that works for customizing drop down list for DateTime objects without losing ability to set selected date on the drop down.
Using simple wrapper class around DateTime object:
public class DisplayDateTime
{
private DateTime dt;
private string shortDate;
public DisplayDateTime(DateTime d)
{
dt = d;
shortDate = dt.ToString("d");
}
public DateTime Date
{
get
{
return dt;
}
}
public string ShortDate
{
get
{
return shortDate;
}
}
}
Which is then used by model:
public List<DisplayDateTime> GetDisplayDates()
{
var displayDates = new List<DisplayDateTime>();
foreach (var d in Dates)
{
displayDates.Add(new DisplayDateTime(d));
}
return displayDates;
}
And then fed to razor like so:
@Html.DropDownList("SelectedDate", new SelectList(Model.GetDisplayDates(), "Date", "ShortDate", Model.SelectedDate));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.