你好,我有什麼應該是一個簡單的問題。我有一組使用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