如何检查用户名是否已经被占用
本文关键字:是否 用户 何检查 检查 | 更新日期: 2023-09-27 18:09:57
我使用数据库优先,并通过ViewModel验证我的输入。但是,我想检查是否已经在db中采取了UserName
。我怎么做呢?这是我设法得到的程度(我可以验证和保存):
[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();
}
这就是如何在Register()方法中检查用户
[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();
}
这将查询并返回数据库中匹配条件或为空的第一个条目db.Users.FirstOrDefault(x => x.UserName == reg.UserName)
所以我只是检查查询是否返回值或null并设置bool(见下面的代码)
注意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");
}