我的视图模型中有这个属性:
[DataType(DataType.DateTime)]
public DateTime? StartDate { get; set; }
如果我想显示日期,或者用日期填充文本框,我有这些:
<%: Model.StartDate %>
<%: Html.TextBoxFor(m => m.StartDate) %>
每当显示日期时,它都会显示为:01/01/2011 12:00:00 AM
但我只想显示 01/01/2011
有没有办法应用带有数据注释的显示格式?我不想去每个显示日期的实例,并添加一些代码来格式化它。
尝试使用以下标签对其进行标记:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
你试过这个吗?
[DataType(DataType.Date)]
在 mvc 4 中,您可以使用 TextBoxFor
轻松完成以下操作。
@Html.TextBoxFor(m => m.StartDate, "{0:MM/dd/yyyy}", new { @class = "form-control default-date-picker" })
因此,您不需要在模型或视图模型类中使用任何数据注释
如果您的数据字段已经是 DateTime 数据类型,则无需使用 [DataType(DataType.Date)]
进行注释;只需使用:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
在 jQuery 上,为您的日历使用 datepicker
$(document).ready(function () {
$('#StartDate').datepicker();
});
在您的 HTML 上,使用 EditorFor
助手:
@Html.EditorFor(model => model.StartDate)
[DataType(DataType.Date)]
" =>这很有帮助
DataFormatString = "{0:MM/dd/yyyy}"
(即使请求正文具有其他格式,即 {"dob":"31/12/1990"}
,也没有得到任何 400)
应用 DataAnnotation,如:
[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]
使用它,但它是一个完整的解决方案:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
评论后
// [DataType(DataType.DateTime)]
使用数据注释属性:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
以下链接的 STEP-7 可以帮助您...
http://ilyasmamunbd.blogspot.com/2014/12/jquery-datepicker-in-aspnet-mvc-5.html
这对我行得通
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
使用 EditorFor 而不是 TextBoxFor
这是我最喜欢在模型中使用注释的方法:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyy}")]
在创建模型时使用以下代码设置您的属性我认为您的问题将得到解决..时间不会出现在数据库中。您不需要添加任何注释。
private DateTime? dob;
public DateTime? DOB
{
get
{
if (dob != null)
{
return dob.Value.Date;
}
else
{
return null;
}
}
set { dob = value; }
}
不定期副业成功案例分享
[DataType(DataType.DateTime)]
吗?DisplayFormat
仅适用于EditorFor
和DisplayFor
助手。@Html.TextBoxFor(model => model.YOUR_DATE, "{0:MM/dd/yyyy}")
,我能够获得要显示的日期。在这里找到这个 [stackoverflow.com/a/14529347/2938775]。