当我使用 Validator.TryValidateObject 时,验证不起作用 [英] Validation does not work when I use Validator.TryValidateObject

查看:38
本文介绍了当我使用 Validator.TryValidateObject 时,验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataAnnotations 不适用于好友类.以下代码始终验证为真.为什么?

DataAnnotations does not work with buddy class. The following code always validate true. Why ?

var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);

var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);

这是伙伴类.

public partial class Customer 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
}

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer 
{ 
    public class CustomerMetaData 
    { 
        [Required(ErrorMessage = "You must supply a name for a customer.")]        
        public string Name { get; set; } 
    } 
}

这是另一个问题,但没有答案.链接文本

Here is another thread with same question., but no answer. link text

推荐答案

我在这里找到了答案:http://forums.silverlight.net/forums/p/149264/377212.aspx

MVC 识别 MetaDataType 属性,但其他项目不识别.验证前需要手动注册元数据类:

MVC recognizes the MetaDataType attribute, but other projects do not. Before validating, you need to manually register the metadata class:

TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer), typeof(CustomerMetadata)), typeof(Customer));

var isValid = Validator.TryValidateObject(new Customer(), context, results, true);

这篇关于当我使用 Validator.TryValidateObject 时,验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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