views:

76

answers:

2

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>
A: 

Your code is working for me.

Ronnie Overby
+1  A: 

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.

Garry Shutler