代码之家  ›  专栏  ›  技术社区  ›  Junior

如何在ASP.NETMVC应用程序的Razor引擎中使用Html.dispar呈现ModelMetadata对象?

  •  3
  • Junior  · 技术社区  · 7 年前

    我想利用 DisplayTemplates razor引擎中的功能,用于自动呈现我的显示视图。

    我扫描我的 Model 找到正确的 ModelMetadata 对于我要显示的每个属性。但我无法使用 Html.DisplayFor 正确地。

    我试着这样展示我的财产

    // First I find the ModelMetadata for the property
    // I call this statement in a loop and each iteration I pass a different PropertyName to get the correct model
    ModelMetadata columnMetadata = elementsMetadata.First(x => x.PropertyName == column.PropertyName);
    
    // I attempted to render the columnMetadata object like so
    Html.DisplayFor(x => columnMetadata.Model)
    

    上面的代码可以“显示正确的值”,但是它没有使用正确的 DisplayTemplate 这导致格式不正确。

    例如,我有一个名为 Currency.cshtml 它只是简单地显示 Model.ToString("C") . 我还有另一个显示模板 Status.cshtml 它接受布尔值并返回“Active”或“Inactive”。两个显示模板都位于 ~/Views/Shared/DisplayTemplates .

    但出于某种原因 Html.DisplayFor() 不是在找合适的 template . 下面是我的一个视图模型的示例

    public class ViewModel
    {
        public string Name { get; set; }
    
        [DataType(DataType.Currency)]
        public decimal Rate { get; set; }
    
        [DataType("Status"), DisplayName("Status")]
        public bool Active { get; set; }
    }
    

    当前“我的视图”显示了 Active 属性和我的 Rate 财产。

    如何正确显示 模型元数据 对象,其中根据属性数据类型使用了正确的显示模板?

    1 回复  |  直到 7 年前
        1
  •  1
  •   user3559349user3559349    7 年前

    ModelMetadata 包含 DataTypeName 属性,它包含 DataTypeAttribute ,这将是您的“货币” Rate 你的财产和“地位” Status 财产。您可以在的第二个参数中使用此值 DisplayFor()

    ModelMetadata columnMetadata = elementsMetadata.First(x => x.PropertyName == column.PropertyName);
    string template = columnMetadata.DataTypeName;
    Html.DisplayFor(x => columnMetadata.Model, template)
    

    还要注意,您可以使用 UIHintAttribute 它还设置 数据类型名 ,例如

    [Display(Name = "Status")] // use this rather that [DisplayName]
    [UIHint("Status")]
    public bool Active { get; set; }