Reputation: 3584
If I use EditFor in MVC my DateTime field show a not formated datetime, If I use a old school html my field don't receive the error class.
<div class="editor-field">
<input type="text" name="EstimateTime" id="EstimateTime" value="<%: (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" %>" />
<%: Html.TextBoxFor(model => model.EstimateTime, new { @value = (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" })%>
<%: Html.ValidationMessageFor(model => model.EstimateTime) %>
</div>
result HTML: Look the difference between the value:
<div class="editor-field">
<input type="text" name="EstimateTime" id="EstimateTime" value="31/10/2013 01:54:42 PM" class="hasDatepicker">
<input id="EstimateTime" name="EstimateTime" type="text" value="10/31/2013 1:54:42 PM" class="input-validation-error text-box single-line">
<span class="field-validation-error">Isn't a date/time valid</span>
</div>
What is the best practices to fix it?
Upvotes: 3
Views: 13645
Reputation: 56
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[DataType(DataType.Date)]
public System.DateTime EstimateTime { get; set; }
This is working for me in the latest version of Chrome
Upvotes: 4
Reputation: 39413
I always use an Editor Template to perfect output control
this is DateTime.cshtml:
@model System.DateTime?
@{
IDictionary<string, object> Attributes = new Dictionary<string, object>();
if (ViewData.ContainsKey("style")) {
Attributes.Add("style", (string)ViewData["style"]);
}
if (ViewData.ContainsKey("autohelp")) {
Attributes.Add("title", (string)ViewData["autohelp"]);
}
if (ViewData.ContainsKey("autofocus")) {
Attributes.Add("autofocus", (string)ViewData["autofocus"]);
}
Attributes.Add("class", "fecha");
Attributes.Add("autocomplete", "off");
}
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), Attributes)
Upvotes: 0
Reputation: 33809
Add DataFormatString
to the property in your model.
public class YourModel
{
[DisplayName("Estimate Time:"),
DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
public System.DateTime EstimateTime { get; set; }
...
}
Upvotes: 2