Split DateTime to Date and Time in ASP.NET MVC
I have read through Scott Hanselman's post on this topic. I found another article that seems to be a simpler approach. The second of which I decided to try.
However, the first portion in creating the EditorTemplates is not working for me. I copied DateTime.ascx and TimeSpan.ascx has the author had them written. Then I split the fields in my view.
<div class="editor-label">
<%= Html.LabelFor(model => model.LeaveRequest.DateOfLeave)%>
</div>
<div class="editor-field">
<div class="date-container">
<%= Html.TextBoxFor(model => model.LeaveRequest.DateOfLeave.Date)%>
</div>
<div class="time-container">
<%= Html.TextBoxFor(model => model.LeaveRequest.DateOfLeave.TimeOfDay)%>
</div>
<div class="clear">
<%= Html.ValidationMessageFor(model => model.LeaveRequest.DateOfLeave)%>
</div>
</div>
The problem I am having is that the behavior I am getting is not the same that that author explained as should happen. Here is a screenshot of my results.
I must be missing something, but I can't tell what. I hav开发者_Python百科e read this article several times and can't see what I am missing. I am guessing there needs to be something to tell the program to us the new EditorTemplates, but I don't know how.
You missed the fact that both Scott's solution and the solution you link to don't do:
<%= Html.TextBoxFor(model => model.LeaveRequest.DateOfLeave.Date) %>
Instead they use:
<%= Html.EditorFor(model => model.LeaveRequest.DateOfLeave.Date) %>
And then utilize a custom editor to limit the field to just the Date (instead of both the date and time).
Scroll down to the Separate the Date / Time fields header of the article you link to and read a little bit closer about custom editor templates.
You can also add a default value on the client side if you'd like.
<%= Html.TextBoxFor(model => model.LeaveRequest.DateOfLeave.Date,
new { @Value= DateTime.Now })%>
This sets the initial Texbox value to the current DateTime
but you can obviously set it to whatever you like.
精彩评论