你好,我有什么应该是一个简单的问题。我有一组使用System.CompontentModel.DataAnnotations的验证。我有一些特定于某些视图模型的验证,所以我很愿意将验证代码放在与我的模型相同的文件中(如在MVC2附带的默认AccountModels.cs文件中)。但是我也有一些适用于几种模型的常见验证(例如有效的电子邮件地址格式)。当我将该验证剪切/粘贴到需要它的第二个模型时,当然由于它们位于相同的命名空间(projectName.Models)中,所以我得到重复的定义错误。所以我想将名称空间中的一个单独的类的通用验证移除,期望我的所有视图模型都能够从那里访问验证。意外的是,验证不再可用。我已经证实他们仍然处于相同的命名空间,并且它们都是公开的。我不希望我会有任何具体的参考(尝试添加使用语句的相同名称空间,但没有解决它,并通过添加引用对话框,项目不能引用自己(使感)。ASP.Net中的常见数据注释MVC2
所以任何想法,为什么那些只是被移动到另一个文件中相同的命名空间公开验证是不可见的模型?
CommonValidations.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace ProjectName.Models
{
public class CommonValidations
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class EmailFormatValidAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value != null)
{
var expression = @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";
return Regex.IsMatch(value.ToString(), expression);
}
else
{
return false;
}
}
}
}
}
而这里的代码,我想使用验证来自:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Growums.Models;
namespace ProjectName.Models
{
public class PrivacyModel
{
[Required(ErrorMessage="Required")]
[EmailFormatValid(ErrorMessage="Invalid Email")]
public string Email { get; set; }
}
}
你的意思是说Visual Studio不能识别你的属性?或编译失败?或者你得到一个运行时错误? – 2010-05-21 22:00:26
编译失败。它在公共验证文件中定义时不会识别验证。它们位于相同的命名空间中。 – 2010-05-27 14:12:08