配置自定义MetadataProvider的视图模型 [英] Configure Custom MetadataProvider for ViewModel

查看:290
本文介绍了配置自定义MetadataProvider的视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有哪些希望能够动态地设置的元数据属性一个ViewModel。例如,我想能够自定义使用其他模特属性值显示名称和验证错误消息。我打算用自定义MetadataProvider要做到这一点,以下布拉德·威尔逊的文章

I have a ViewModel for which want to be able to set Metadata properties dynamically. For example I would like to be able to customise the DisplayName and validation error messages using the value of other model properties. I plan to do this with a custom MetadataProvider, following Brad Wilson's article.

我想要的提供商只与选定的ViewModels使用。所以我的问题是,我该如何配置?我一直在使用 ModelMetadataProviders.Current =新MyModelMetadataProvider()看到的例子,但这将presumably使用自定义提供的所有模型类的实体。是否有可能配置一个供应商的单一视图模型?

I want the provider only to be used with selected ViewModels. So my question is, how do I configure that? I have seen examples using ModelMetadataProviders.Current = new MyModelMetadataProvider(), but this would presumably use the custom provider for all model classes entities. Is it possible to configure a provider for a single ViewModel?

推荐答案

我是pretty肯定改变视图模型当前模型元数据提供者是不是安全的,一旦你开始越来越多的用户在网站上,更不用说线安全。你也许可以使用属性,方法,但你还是得实现自己的ModelMetadataProvider并在您的应用程序开始时设置为电流,然后检查是否有某些属性,并确定您ModelMetaData返回,如果有没有再落下通过对基实现。虽然说实话,那你在谈论的限制,有它只能处理选定的视图模型量,但是没有被允许知道或测试这些视图模型?这听起来像你做错了什么......别处

I'm pretty sure changing the current model metadata provider in the ViewModel is not safe once you start getting multiple users on the site, let alone thread safe. You might be able to use the attribute method but you'll still have to implement your own ModelMetadataProvider and set it to Current at the start of your app, then inspect for certain attributes and determine your ModelMetaData to return, if there are none then fall through to the base implementation. Though to be honest, the amount of restrictions that you're talking about, having it only handle selected view models but not being allowed to know or test for those view models? It sounds like you're doing something wrong elsewhere...

更新:当我需要我创建了一个看起来像这样一个ModelMetadata提供商...

UPDATE: When I needed a ModelMetadata provider I created one that looks something like this...

public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        if ((containerType != typeof(MyType))
            return base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        //setup custom ModelMetadata here
    }
}

这篇关于配置自定义MetadataProvider的视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆