3

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?

2
  • It swapped the day for the month. What's the big deal? Commented Oct 31, 2013 at 3:59
  • the problem is, if I use Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") the date are show formated MM/dd/..... Commented Oct 31, 2013 at 4:03

3 Answers 3

4
[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

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think chrome has any relation to it.
2

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; }
   ...
}

1 Comment

You should also probably specify ApplyFormatInEditMode = true in the DisplayFormat attribute.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.