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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With