I have a view with textbox bound to a DateTime model field.
The view:
@Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker", id = "startDate" })
The model:
[Required(ErrorMessageResourceType = typeof(Resources.ValidationMessages), ErrorMessageResourceName = "GeneralRequired")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Display(Name = "StartDate", ResourceType = typeof(Resources.Something))]
public DateTime? StartDate { get; set; }
View uses jQuery datepicker to handle date input. Jquery generates only date, but I as far as I know there's no only date type in C#.
I use also custom DateTime model binder but it's rather to big to post its code (tl;dr ;)).
When user input for instance 15-01-2015 in the textbox and post it to the method the model binder converts it properly (to a 15-01-2015 12:00). The problem is when the validation is fired because there are two datetime fields on the form and if user enters only one of them then action method returns view with validation messages. Already entered field should be still filled obviously. The problem is that when controller's action method returns view it places a date time into textbox, not only a date.
Is there any method we can use to pass only date instead of date and time to a bound field in a view? Or maybe keep field bound but display only value.Date in textbox?
EDIT:
I've tried to apply Hugo Delsing's solution but faced next issue. Basically we're going to use EditorTemplate for DateTime field of the model. DateTime.cshtml looks as follows:
@model System.DateTime?
@if (Model == null)
{
@Html.TextBox(
string.Empty,
"",
new { @class = "datepicker", @type = "text" })
}
else
{
@Html.TextBox(
string.Empty,
Model.ToString("dd-MM-yyyy"),
new { @class = "datepicker", @type = "text" })
}
The problem appears as far as I understand in the line
Model.ToString("dd-MM-yyyy")
Because thrown error is
Shared\EditorTemplates\DateTime.cshtml(13): error CS1501: No overload for method 'ToString' takes 1 arguments
As far as I understand it's like that else is evaluated always, am I right? Is there any solution to achieve what I want without moving if statement to a main view and building something like this?
@if(model.StartDate.HasValue)
{
@Html.EditorFor(model => model.StartDate, "TemplateFirst")
}
else
{
@Html.EditorFor(model => model.StartDate, "TemplateSecond")
}