在模型和控制器中创建自定义错误消息

假设你有以下类:

public class PersonInfo
{
    public int ID { get; set; }

    [Display(Name = "First Name")]
    [Required(ErrorMessage = "Please enter your first name!")]
    public string FirstName{ get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Please enter your last name!")]
    public string LastName{ get; set; }

    [Display(Name = "Age")]
    [Required(ErrorMessage = "Please enter your Email Address!")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string EmailAddress { get; set; }
}

如果你的 ModelState.IsValid 返回 false,则会显示这些自定义错误消息。

但是,你和我知道每个人只能有 1 个电子邮件地址,否则你将向可能错误的人和/或多个人发送电子邮件。这是控制器中的检查发挥作用的地方。因此,我们假设人们正在为你创建帐户,以便通过创建操作进行保存。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID, FirstName, LastName, EmailAddress")] PersonInfo newPerson)
{
    if(ModelState.IsValid) // this is where the custom error messages on your model will display if return false
    {
        if(database.People.Any(x => x.EmailAddress == newPerson.EmailAddress))  // checking if the email address that the new person is entering already exists.. if so show this error message
        {
            ModelState.AddModelError("EmailAddress", "This email address already exists! Please enter a new email address!");
            return View(newPerson);
        }
        
        db.Person.Add(newPerson);
        db.SaveChanges():
        return RedirectToAction("Index");
    }

    return View(newPerson);
}

我希望这能帮助别人!