如何编辑模板/显示模板识别分配给它们的任何属性? [英] How can Editor Templates / Display Templates recognize any Attributes assigned to them?

查看:129
本文介绍了如何编辑模板/显示模板识别分配给它们的任何属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要一个 [必需] 属性添加到我的的DateTime 编辑模板,这样我就可以添加相应的验证方案或 DataType.Date 属性,所以我知道什么时候应该只显示日期。但我无法弄清楚如何获得,说哪些属性编辑器模板已分配给它的元数据。

I want to add a [Required] attribute to my DateTime editor template so that I can add the appropriate validation schemes or a DataType.Date attribute so I know when I should only display dates. But I can't figure out how to get the metadata that says which attributes the Editor Template has assigned to it.

推荐答案

内置的属性,如 [必需] 上的元数据分配不同的属性(请参阅博客文章我已经在我的答案,以了解更多)结束的联系。例如:

The built-in attributes, such as [Required] assign different properties on the metadata (see the blog post I have linked at the end of my answer to learn more). For example:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }
}

将会分配:

@{
    var isRequired = ViewData.ModelMetadata.IsRequired;
}

在相应的编辑器/显示模板。

in the corresponding editor/display template.

如果你有一个自定义属性:

And if you had a custom attribute:

public class MyCustomStuffAttribute : Attribute, IMetadataAware
{
    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["customStuff"] = "some very custom stuff";
    }
}

和视图模型装饰着它:

public class MyViewModel
{
    [MyCustomStuff]
    public string Foo { get; set; }
}

在相应的编辑器/显示模板,你可以获取这样的:

in the corresponding editor/display template you could fetch this:

@{
    var myCustomStuff = ViewData.ModelMetadata.AdditionalValues["customStuff"];
}

此外,你绝对应该阅读布拉德·威尔逊的<一个href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html\">series博客文章的什么ModelMetadata和ASP.NET MVC的模板,以及如何使用它。

Also you should absolutely read Brad Wilson's series of blog posts about what ModelMetadata and templates in ASP.NET MVC is and how to use it.

这篇关于如何编辑模板/显示模板识别分配给它们的任何属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆