Question

I already followed every step in the following tutorial but got some problem. My purpose is to use model binder to bind date and time and then save in a datetime field. http://devblog.lundy.us/2010/09/28/date-time-picker-asp-net-mvc-jquery-part-1/

I just have a quick question: How can he implement the following code in the edit view?

"<%: Html.EditorFor(model => model.Start.Date)%>" 

How did he get Start.Date?
Because he only has Start and End in his model. Where did he define variable Date?

And I got an error when I implement above code: 'System.Nullable' doesn't contain a definition for 'Date'

I'm sure I have exactly the same Model and DateTimeModelBinder.cs as his code.

Please tell me why I can't use model => model.Start.Date Or tell me any tutorial explicitly teach me how to bind date and time.

Thanks!!

Was it helpful?

Solution

The DateTime data type in .NET exposes some properties, such as .Date (the same date value, but with time set to 12am), .TimeOfDay, .Year, etc. The example blog post you're referring to uses DateTime, thus all of these properties are available. Also note that DateTime is a value type and cannot be null.

Your model, on the other hand, uses a property of type DateTime? which is a reference type and can be null. Nullable types are reference type wrappers around value types. All of them expose a property called .HasValue of type bool, and a property .Value of the type that the wrapping nullable type corresponds to. In case of DateTime?, the type of the .Value property is DateTime.

With your model the following should work:

<%: Html.EditorFor(model => model.Start.Value.Date)%>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top