我想为DateTime
属性创建一个DisplayTemplate。
例如,我有以下模型:
public class MyModel
{
[DataType(DataType.Date)]
public DateTime? Date { get; set; }
[DataType(DataType.Time)]
public DateTime? TimeFrom { get; set; }
[DataType(DataType.Time)]
public DateTime? TimeUntil { get; set; }
[DataType(DataType.DateTime)]
public DateTime? SomeDate { get; set; }
}
在我看来:
@Html.DisplayFor(x => x.Date) // Expected output: 13.11.2015
@Html.DisplayFor(x => x.TimeFrom) // Expected output: 08:00
@Html.DisplayFor(x => x.TimeUntil) // Expected output: 12:00
@Html.DisplayFor(x => x.SomeDate) // Expected output: 15.11.2015 08:55
在我的DisplayTemplate中,我有以下代码:
@using System.ComponentModel.DataAnnotations
@using System.Reflection
@model DateTime?
@{
var type = Model.GetType();
var attribute = type.GetCustomAttribute(typeof (DataTypeAttribute)) as DataTypeAttribute;
}
@if (Model != null)
{
if (attribute != null)
{
if (attribute.DataType == DataType.Date)
{
@Model.Value.ToShortDateString()
}
if (attribute.DataType == DataType.Time)
{
@Model.Value.ToShortTimeString()
}
else
{
@Model.Value
}
}
else
{
@Model.Value
}
}
不幸的是,找不到DataTypeAttribute
。
找到的唯一CustomAttributes是Serializable
和__DynamicallyInvokable
- 属性。
在模型中,我们始终拥有DateTimes
的DataType属性。
如何找到当前的DataTypeAttribute
?
答案 0 :(得分:1)
请注意,您正在搜索分配给DateTime?
类型本身的属性,而不是MyModel
类的属性。没有在这些中找不到这个数据模型属性。
所有内置数据模型属性都会填充ViewData.ModelMetadata
对象,因此您应该可以使用以下命令访问数据类型的名称:
ViewData.ModelMetadata.DataTypeName
不幸的是,由于某种原因,这是一个字符串,因此您可能需要将其与DataType.Date.ToString()
之类的内容进行比较。
有关其他模型元数据属性的更多信息,请参阅ModelMetadata class description。
答案 1 :(得分:0)
你能试试DisplayFormat吗? http://www.codeproject.com/Articles/775220/ASP-Net-MVC-What-are-the-uses-of-Display-DisplayNa
public class MyModel
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
public DateTime? Date { get; set; }
[DataType(DataType.Time)]
public DateTime? TimeFrom { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
public DateTime? TimeUntil { get; set; }
[DataType(DataType.DateTime)]
public DateTime? SomeDate { get; set; }
}