这是控制器:
public class UserController : Controller
{
ResturantEntities db = new ResturantEntities();
public ActionResult Index()
{
var data = db.User.OrderByDescending(z => z.ID).Select(s => s).ToList();
return View(data);
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(UserVM obj)
{
if (ModelState.IsValid)
{
User newobj = new User();
newobj.UserName = obj.UserName;
newobj.Email = obj.Email;
newobj.Password = obj.Password;
newobj.Address = obj.Address;
db.User.Add(newobj);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Register");
}
}
}
我想在newobj.Email = obj.Email;
之前添加一个if条件,以检查电子邮件是否存在于db中;如果不存在,则将其添加。
答案 0 :(得分:1)
首先欢迎您使用Stack Overflow。
现在如下编写您的Register
POST
方法:
[HttpPost]
public ActionResult Register(UserVM obj)
{
if (ModelState.IsValid)
{
var isEmailAlreadyExists = db.User.Any(x => x.Email == obj.Email);
if(isEmailAlreadyExists)
{
ModelState.AddModelError("Email", "User with this email already exists");
return View(obj)
}
User newobj = new User();
newobj.UserName = obj.UserName;
newobj.Email = obj.Email;
newobj.Password = obj.Password;
newobj.Address = obj.Address;
db.User.Add(newobj);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj)
}