asp.net mvc 3 - remove time from date

﹥>﹥吖頭↗ 提交于 2020-01-15 15:28:40

问题


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


回答1:


You need to set the ApplyFormatInEditMode property of the DisplayFormatattribute 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.




回答2:


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



来源:https://stackoverflow.com/questions/11179027/asp-net-mvc-3-remove-time-from-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!