开发者

How can Editor Templates / Display Templates recognize any Attributes assigned to them?

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; }
}

would assign:

@{
    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";
    }
}

and a view model decorated with it:

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"];
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜