MVC - 如何检查用户名是否尚未使用?

时间:2016-10-01 00:01:32

标签: c# asp.net-mvc entity-framework

我正在使用数据库优先,我通过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();
    }

2 个答案:

答案 0 :(得分:4)

这是你在Register()方法

中检查用户的方法
{{1}}

答案 1 :(得分:1)

这将查询并返回匹配条件OR的db中的第一个条目 db.Users.FirstOrDefault(x => x.UserName == reg.UserName)

所以我只检查该查询是返回值还是null并设置bool(参见下面的代码)

注意x,您可以使用其他字母或单词。也许data => data.UserName....row => row.UserName...result => result.UserName...,它只代表数据库的模型

类似的东西(重新安排了一些代码)

[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");
}