I am having a model in with a DateTime property:
public DateTime? DateNaissance { get; set; }
and a View with a @Html.TextBoxFor for the property
@Html.TextBoxFor(model => model.DateNaissance)
All I want is to get the date typed, however, when I type in 01/06/2012 as date I am having the "01/06/2012 00:00:00" in the controller
All I want is to get the date, why the time is added ?, how to automatically remove it ?
I tried out without success:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
Thanks
You need to set the ApplyFormatInEditMode
property of the DisplayFormat
attribute to true and then use EditorFor
instead of TextboxFor
:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
@Html.EditorFor(model => model.DateNaissance)
Update
If you need to do this for every date, you can also put a file called DateTime.cshtml in \Views\Shared\EditorTemplates\ with this in it:
@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : string.Empty))
This will use "dd/MM/yyyy" for DateTimes when you use EditorFor
.
It's worth to say that you will get always the time since your object is of DateTime type. If you want to use only the Date, on your controller you need to get only the Date part with DateNaissance.Date, but again the object will always have the time part on it