0
我是.net MVC的新手,但我正在努力。我試圖做一個自定義的DataAnnotation驗證器來檢查一個電子郵件地址是否已經註冊。我正在使用LINQ to SQL。我的模型如下:自定義驗證,用於檢查數據庫中是否存在電子郵件。幫幫我!
// Model
public class UsersRepository
{
private DigitalentDataContext db = new DigitalentDataContext();
BaseController baseController = new BaseController();
//
// Add talent user
public void AddTalentUser(User user, TalentDetail talentDetail)
{
user.TalentDetails.Add(talentDetail);
db.Users.InsertOnSubmit(user);
db.SubmitChanges();
string activationID = user.ActivationID.ToString();
string activationEmail = user.Email;
baseController.SendConfEmail(activationID, activationEmail);
}
public IQueryable<User> GetAllUsers()
{
return db.Users;
}
}
//Validation
[MetadataType(typeof(UserValidation))]
public partial class User { }
[Bind(Exclude = "UserID")]
[ExistingEmailCheck("Email", ErrorMessage="Email address already registered")]
public class UserValidation
{
[Required(ErrorMessage = "First name required"), StringLength(20, MinimumLength=3, ErrorMessage = "Must be between 3 and 20 characters")]
public string FirstName { get; set; }
...
}
public class ExistingEmailCheckAttribute : ValidationAttribute
{
public ExistingEmailCheckAttribute(string emailToCheck) {
EmailToCheck = emailToCheck;
}
public string EmailToCheck { get; private set; }
private UsersRepository _UserRep = new UsersRepository();
public override bool IsValid(object value)
{
int existingEmailCount = _UserRep.GetAllUsers().Where(g => g.Email == EmailToCheck).Count();
return existingEmailCount == 0;
}
}
控制器代碼:
[HttpPost]
public ActionResult Signup(User user, TalentDetail talentDetail)
{
if (ModelState.IsValid) {
user.ActivationID = System.Guid.NewGuid();
user.ActivationStatus = false;
user.DateCreated = DateTime.Now;
userRepository.AddTalentUser(user, talentDetail);
return RedirectToAction("confirm", "login");
}
return View(user);
}
其他所有驗證工作,但ExistingEmailCheck沒有。沒有錯誤,沒有。有任何想法嗎??非常感謝幫助。
Shahid
「看起來不起作用?」意思?它可以工作,也可以不工作,如果不工作,那是什麼意思,異常,不驗證,不查詢,斷點不打?你的控制器代碼是什麼? – jfar 2010-08-12 17:56:17
@Gnomo,請詳細說明一下? – shahidaltaf 2010-08-12 18:12:18
在我看來,使用屬性來執行業務邏輯是非常糟糕的形式。確認電子郵件地址在插入時是唯一的,並引發異常。 – Ryan 2010-08-12 18:37:59