ASP.NET MVC 自定义 MetadataProvider
我正在构建一个自定义 MetadataProvider,我想在 CreateMetadata
方法中访问实际模型值。
public class IcpMetadataProvider : AssociatedMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = new ModelMetadata(this, containerType, modelAccessor, modelType, propertyName);
//Is null when the model is of reference type
var model = metadata.Model;
return metadata;
}
}
当当前模型值是字符串类型时,模型值可以在metadata.Model
中找到。但是当模型是引用类型时,该值为 null。
或者也许有什么方法可以将自定义数据传递给此方法?
I'm building a custom MetadataProvider and I'd like to access the actuall model value in the CreateMetadata
method.
public class IcpMetadataProvider : AssociatedMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = new ModelMetadata(this, containerType, modelAccessor, modelType, propertyName);
//Is null when the model is of reference type
var model = metadata.Model;
return metadata;
}
}
When the current model value is of type string, the model value can be found in metadata.Model
. But when the model is of reference type the value is null.
Or maybe is there any way to pass custom data to this method ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
引用 Brad Wilson 的话,您需要“调用 base.CreateMetadata,以便获得填充了 DataAnnotations 中的值的 ModelMetadata,然后用您自己的属性中的值对其进行补充。”
参考链接:http://bradwilson.typepad。 com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html
Quoting Brad Wilson, you need to "Call base.CreateMetadata so that you can get the ModelMetadata that’s filled with values from DataAnnotations, and then just supplement it with values from your own attributes."
Ref link: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html