2013-02-13 127 views
0

asp.net mvc服務器端驗證JavaScript在瀏覽器中被禁用嗎?我在我的模態類中使用「遠程」,它僅在啓用javascript時驗證,它在JavaScript禁用時不驗證。ASP.Net MVC驗證(服務器端)

我的問題的情景是我在我的數據庫中有一個表與數據類型爲varchar的列「代碼」。任何人都會插入他們必須插入唯一代碼的數據。 請幫助我

回答

2

我建議忘記remote,因爲如果您使用的是代碼優先的實體框架,您的表中不能有多於一個unique列。我只是寫這樣的代碼:

[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public ActionResult Register(RegisterModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Insert a new user into the database 
     using (UsersContext db = new UsersContext()) 
     { 
      UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower()); 
      try 
      { 
       // Check if email already exists 
       if (email == null) 
       { 
        WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email }); 
        WebSecurity.Login(model.UserName, model.Password); 
        return RedirectToAction("Index", "Home"); 
       } 
       else 
       { 
        ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address."); 
       } 
      } 
      catch (MembershipCreateUserException e) 
      { 

       ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); 
      } 
     } 
    } 

用你想驗證的屬性替換電子郵件。在發佈後,這將與數據庫中已存在的條目進行比較,並根據結果進行反饋。如果存在這樣的數據,則拋出異常。