如何在编辑器模板中测试 [AllowHtml] 属性?
How can I test for [AllowHtml] attribute within an editor template?
我希望能够在编辑器模板中测试 属性 的 [AllowHtml] 属性。
它似乎没有潜伏在 ViewData.ModelMetadata
中。
我尝试遍历 ViewData.ModelMetadata.AdditionalValues
以查看它是否存在,但它似乎不存在。
我已经搜索了 Google 和 Brad Wilson's post on templates,但我无法在任何地方找到答案。
我相信您必须在模板中做一些繁重的工作,例如:
var allowHtmlAttribute = this.ViewData.ModelMetadata
.ContainerType
.GetProperty(this.ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(AllowHtmlAttribute), false)
.Select(a => a as AllowHtmlAttribute)
.FirstOrDefault(a => a != null);
现在想想,如果有扩展方法就好了!
public static class ModelMetadataExtensions
{
public T GetPropertyAttribute<T>(this ModelMetadata instance)
where T : Attribute
{
var result = instance.ContainerType
.GetProperty(instance.PropertyName)
.GetCustomAttributes(typeof(T), false)
.Select(a => a as T)
.FirstOrDefault(a => a != null);
return result;
}
}
然后
var myAttribute = this.ViewData.ModelMetadata
.GetPropertyAttribute<AllowHtmlAttribute>();
我希望能够在编辑器模板中测试 属性 的 [AllowHtml] 属性。
它似乎没有潜伏在 ViewData.ModelMetadata
中。
我尝试遍历 ViewData.ModelMetadata.AdditionalValues
以查看它是否存在,但它似乎不存在。
我已经搜索了 Google 和 Brad Wilson's post on templates,但我无法在任何地方找到答案。
我相信您必须在模板中做一些繁重的工作,例如:
var allowHtmlAttribute = this.ViewData.ModelMetadata
.ContainerType
.GetProperty(this.ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(AllowHtmlAttribute), false)
.Select(a => a as AllowHtmlAttribute)
.FirstOrDefault(a => a != null);
现在想想,如果有扩展方法就好了!
public static class ModelMetadataExtensions
{
public T GetPropertyAttribute<T>(this ModelMetadata instance)
where T : Attribute
{
var result = instance.ContainerType
.GetProperty(instance.PropertyName)
.GetCustomAttributes(typeof(T), false)
.Select(a => a as T)
.FirstOrDefault(a => a != null);
return result;
}
}
然后
var myAttribute = this.ViewData.ModelMetadata
.GetPropertyAttribute<AllowHtmlAttribute>();