Reputation: 175
I have a dropdownlistfor which lists selectable dates. I want to pre-select a certain date but even though it's marked as "Selected" it doesn't show as the selected when looking at the dropdownlist.
<%=Html.DropDownListFor(model => model.SelectDropOfDate, Model.DropOffDates, new { id = "dropOfDate" })%>
In one thread that I read they said that "model.SelectDropOfDate" (in this case) is the selected item and if that's the case, should I select the value or the text in order for it to match the one in the list?
(the list of dates).Where(x=>x.Selected).Select(z=>z.Value).ToString();
(Ps: I've tried both value and text and none of them worked)
Any ideas?
Upvotes: 0
Views: 647
Reputation: 175
My appologies, there was a dumb javascript overwriting my selected which screwed things up. I did create a testproject to verify the suggestions here though and here's what I found out (for others that read this thread):
The selectedDropOfDate does not have to be filled in, in fact, it didnt work at all when I had that filled in. Having the List have one item that is marked as selected = true works well enough.
Example code
Model:
public class Home
{
public string Selected { get; set; }
public List<SelectListItem> Items { get; set; }
}
Controller:
public ActionResult Index()
{
var model = new Home();
model.Items = GetItems(DateTime.Now, DateTime.Now.AddDays(3));
return View(model);
}
private List<SelectListItem> GetItems(DateTime start, DateTime end)
{
var dates = new List<DateTime>();
for (double i = 0; i < 100; i++)
{
dates.Add(start.AddDays(i + 1));
}
var selectList = new List<SelectListItem>();
selectList.AddRange(dates.Select(x => new SelectListItem
{
Selected = x.Date == end.Date,
Text = x.ToString("d.M.yyyy"),
Value = x.ToString("d/M/yyyy", new DateTimeFormatInfo())
}));
return selectList;
}
View:
<%= Html.DropDownListFor(model => model.Selected, Model.Items) %>
Upvotes: 0
Reputation: 1230
It seems like DropDownListFor
in asp.mvc has this bug,the 'selected' will not work i thought beacuse the htmlhelper of Lamda Expression covered the 'selected' property.So just make sure model.SelectDropOfDate=departureDate.ToString("d/M/yyyy", new DateTimeFormatInfo())
has run.
I have tried this in Mvc3 and it will chosen write item when the value really matches.
Upvotes: 0
Reputation: 1039100
You should set the value of the SelectDropOfDate
property on your model instead to the corresponding Value (not Text). For example:
model.SelectDropOfDate = departureDate.ToString("d/M/yyyy", new DateTimeFormatInfo());
Also notice that the value must have an exact match in order for the corresponding element to be preselected.
Upvotes: 1