Я хочу создать DisplayTemplate для 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
найдено. Найдены только следующие атрибуты: Serializable
и __DynamicallyInvokable
-Attributes.
В модели у нас всегда есть атрибут DataType для DateTimes
. Как найти текущий DataTypeAttribute
?
Я считаю, что вам нужно будет ввести свой шаблон 'MyModel'. Тип BCL Nullable не будет знать вашу аннотацию. –