在模型和控制器中建立自定義錯誤訊息

假設你有以下類:

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

我希望這能幫助別人!