2016-10-01 59 views
1

我使用數據庫優先和我通過ViewModel驗證我的輸入。但是,我想檢查是否已經在db中使用了UserName。我怎麼做?這是多遠我設法(我可以驗證並保存):MVC - 如何檢查用戶名是否已被使用?

[Required] 
[StringLength(50)] 
[MinLength(3, ErrorMessage = "You must at least have 3 letters")] 
public string UserName { get; set; } 

而下面是在控制我的註冊代碼:

[HttpGet] 
    public ActionResult Register() { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Register(UserVIewModel reg) { 
     if (ModelState.IsValid) 
     { 
      var m = new User { 
       UserName = reg.UserName, 
       Email = reg.Email, 
       FirstName = reg.FirstName, 
       LastName = reg.LastName, 
       Password = reg.Password 
      }; 

      db.Users.Add(m); 
      db.SaveChanges(); 

      return RedirectToAction("Login"); 

     } 
     return View(); 
    } 

回答

4

這是你該怎麼辦檢查用戶裏面寄存器()方法

[HttpPost] 
public ActionResult Register(UserVIewModel reg) { 
    if (ModelState.IsValid) 
    { 

     if (db.Users.Where(u => u.UserName == reg.UserName).Any()) 
     { 
      //Do what do u need to do... 
     } 
     else 
     { 
      var m = new User { 
      UserName = reg.UserName, 
      Email = reg.Email, 
      FirstName = reg.FirstName, 
      LastName = reg.LastName, 
      Password = reg.Password 
      }; 

      db.Users.Add(m); 
      db.SaveChanges(); 

      return RedirectToAction("Login"); 
     } 
    } 
    return View(); 
} 
+0

正是我在尋找,謝謝。順便說一句,有沒有什麼好的方法來返回「驗證信息」? – Nyprez

+0

有很多方法。一種方法是在ViewBag中設置驗證消息,在視圖中將其分配給可視控件。你可以谷歌樣本。 – RajN

+0

嗯,謝謝你的工作:) – Nyprez

1

這將查詢並返回的分貝的標準匹配的或爲空 的第一項

所以我只是檢查,如果該查詢返回的值或空,並設置一個布爾值(見下面的代碼)

注意x,您可以用另一個字母或單詞。也許data => data.UserName....row => row.UserName...result => result.UserName...,它只是代表了DB

像這樣的模型(重排的碼位爲好)

[HttpPost] 
public ActionResult Register(UserVIewModel reg) { 
    if (!ModelState.IsValid) 
    { 
     return View(model); 
    } 

    // here is the main answer to your question 
    bool userExists = db.Users.FirstOrDefault(x => x.UserName == reg.UserName) != null; 

    // and then use the bool to see if you need to return an error 
    if (userExists) { 
     // I'm not 100% sure about this part so double-check this 
     // but I think it's pretty close to this 
     ModelState.AddModelError("UserName","UserName taken"); 
     return View(model); 
    } 


    // If the userExists = false then code continues here 
    var m = new User { 
     UserName = reg.UserName, 
     Email = reg.Email, 
     FirstName = reg.FirstName, 
     LastName = reg.LastName, 
     Password = reg.Password 
    }; 

    db.Users.Add(m); 
    db.SaveChanges(); 

    return RedirectToAction("Login"); 
} 
+0

'db.Users.Where(u => u.UserName == reg.UserName).Any()'這@raj放在他的回答中比創建bool好,但概念是相同的 – Francisc0