gpt4 book ai didi

c# - 在 DisplayTemplate 中访问模型属性

转载 作者:行者123 更新时间:2023-11-30 12:42:28 25 4
gpt4 key购买 nike

我想为 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-Attributes。

在模型中,我们始终有一个用于DateTimes 的DataType 属性。如何找到当前的 DataTypeAttribute

最佳答案

请注意,您正在搜索分配给 DateTime? 类型本身的属性,而不是 MyModel 类的属性。在这些中找不到此数据模型属性。

所有内置数据模型属性都填充了 ViewData.ModelMetadata 对象,因此您应该能够通过以下方式访问数据类型的名称:

ViewData.ModelMetadata.DataTypeName

不幸的是,出于某种原因这是一个字符串,因此您可能需要将它与 DataType.Date.ToString() 之类的内容进行比较。

有关其他模型元数据属性的更多信息,请参阅 ModelMetadata class description .

关于c# - 在 DisplayTemplate 中访问模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33695117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com