ksa*_*ang 3 .net data-annotations
我正在使用VS2008 SP1,WCF Ria Service 2009年7月CTP.我发现MetadataType在部分类模式下不起作用,真的不知道我错过了什么:
工作:-
public partial class Person
{
private string _Name;
[Required(AllowEmptyStrings=false, ErrorMessage="Name required entry")]
[StringLength(3)]
public string Name
{
set{_Name = value;}
get{return _Name;}
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person { Name="123432" };
List res = new List();
Validator.TryValidateObject(p,new ValidationContext(p,null,null),
res,true);
if (res.Count > 0)
{
Console.WriteLine(res[0].ErrorMessage);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
不行
public partial class Person
{
private string _Name;
public string Name
{
set{_Name = value;}
get{return _Name;}
}
}
[MetadataType(typeof(PersonMetadata))]
public partial class Person
{
}
public partial class PersonMetadata
{
[Required(AllowEmptyStrings=false, ErrorMessage="Name required entry")]
[StringLength(3)]
public string Name;
}
class Program
{
static void Main(string[] args)
{
Person p = new Person { Name="123432" };
List res = new List();
Validator.TryValidateObject(p,new ValidationContext(p,null,null),
res,true);
if (res.Count > 0)
{
Console.WriteLine(res[0].ErrorMessage);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我在这里找到答案:http://forums.silverlight.net/forums/p/149264/377212.aspx
在验证之前,您需要手动注册元数据类:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Person), typeof(PersonMetadata)), typeof(Person));
List<ValidationResult> res = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(p, new ValidationContext(p, null, null), res, true);
Run Code Online (Sandbox Code Playgroud)
(原始答案如下)
问题不在于您的部分类,而是Validator.TryValidateObject似乎无法识别MetaDataType属性.我有同样的问题 - MVC 2中的内置验证识别元数据类,但TryValidateObject没有.
请参阅以下内容: 使用Validator类验证DataAnnotations 当我使用Validator.TryValidateObject时,验证不起作用
作为旁注,我不知道是否有必要,但我在元数据类中看到的所有示例都使用每个属性的默认get/set:
[Required(AllowEmptyStrings=false, ErrorMessage="Name required entry")]
[StringLength(3)]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6737 次 |
| 最近记录: |