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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
标签:
asp.net-mvc-3