Trouble with ASP.NET MVC SelectList with IEnumerable<DateTime>
As usual, having trouble with SelectList in the MVC framework. The selected value is never set for some reason:
public class MyViewModel
{
public DateTime? SelectedServiceTime { get; set; }
public IEnumerable<DateTime> AvailableServiceTimes { get; set; }
public SelectList ServiceTimesList
{
get
{
SelectList selectList = new SelectList(AvailableServiceTimes开发者_如何转开发, SelectedServiceTime.ToString());
return selectList;
}
}
}
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyViewModel>" %>
<asp:Content ID="MainContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<%using (Html.BeginForm()) { %>
<%:Html.DropDownListFor(x => x.SelectedServiceTime, Model.ServiceTimesList, new { size = 6 }) %><br />
<input type="submit" name="nextButton" value="Next" />
<%} %>
</asp:Content>
It could be a problem with date format parsing. Try formatting your dates with "yyyy-MMM-dd"
rather than relying on .ToString()
. This parses correctly no matter what culture is in the browser and the server (assuming you only care about the date, add the time part if needed).
If that does not work, try adding a default value of something like DateTime.MinValue
and checking for that rather than using DateTime?
. This isn't usually a problem but something worth trying to try and work out where the problem is.
精彩评论