Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 205
Jonn Avatar asked Sep 05 '11 22:09

Jonn


1 Answers

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.

like image 57
Darin Dimitrov Avatar answered Jan 03 '23 20:01

Darin Dimitrov