数据注释不适用于 [Required(Error Message = ......)]

Data annotation is not working for [Required(Error Message = ......)]

我不理解 ModelState.IsValid,我相信这是我在 CreateContact Action 方法中所缺少的。请解释一下,我应该如何检查 If(ModelState.IsValid)?我的验证不起作用。如果文本框(或模型属性)为空,我应该会看到一条错误消息。如果它符合验证规则,我应该能够将日期保存到数据库中,并在单击提交按钮后重定向到 "AddContactDetails" 操作方法。

查看模型

public class CreateContactStepOne
{
    public int PersonID { get; set; }

    [Required(ErrorMessage = "Nickname is required and keep it short upto 10 characters")]
    [Display(Name = "Nickname:")]
    [RegularExpression("^[a-zA-Z. ]{1,10}$", ErrorMessage = "Only letters and no numbers or special characters allowed. Also, limit your First Name to 10 character length.")]
    public string NickName { get; set; }

    [Required(ErrorMessage = "First Name is required")]
    [Display(Name = "First Name:")]
    [RegularExpression("^[a-zA-Z. ]{1,25}$", ErrorMessage = "Only letters and no numbers or special characters allowed. Also, limit your First Name to 25 character length.")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    [Display(Name = "Last Name: ")]
    [RegularExpression("^[a-zA-Z. ]{1,25}$", ErrorMessage = "Only letters and no numbers or special characters allowed. Also, limit your Last Name to 25 character length.")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Select Phone type and enter a phone number below")]
    [Display(Name = "Phone: ")]
    //[RegularExpression("^[0-9-]{1,12}$", ErrorMessage = "Please enter the correct format. Example 717-123-4567")]
    public Phone PhoneNumber { get; set; }

    [Required(ErrorMessage = "Phone number is required")]
    [RegularExpression(@"^\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$", ErrorMessage = "Please enter the correct format. Example (717) 123-4567")]
    public string ContactPhoneNumber { get; set; }

}

public enum Phone
{
    Mobile, Office, Home
}

家庭控制器

[HttpPost]
    public ActionResult CreateContact(CreateContactStepOne contact)
    {

            person p = new person();
            p.FirstName = contact.FirstName;
            p.LastName = contact.LastName;

            if (contact.PhoneNumber == Phone.Home)
            {
                p.HomePhone = contact.ContactPhoneNumber.ToString();
            }
            else if (contact.PhoneNumber == Phone.Mobile)
            {
                p.MobilePhone = contact.ContactPhoneNumber.ToString();
            }
            else if (contact.PhoneNumber == Phone.Office)
            {
                p.OfficePhone = contact.ContactPhoneNumber.ToString();
            }

            PhonebookEntities db = new PhonebookEntities();

            db.people.Add(p);
            db.SaveChanges();
            //Redirect to ActionMethod ContactDetails and passes the personID as parameter
            return RedirectToAction("AddContactDetails", new { id = p.PersonID });

    }

    public ActionResult AddContactDetails(int id)
    {

        PhonebookEntities db = new PhonebookEntities();
        person existingPerson = db.people.Where(x => x.PersonID == id).FirstOrDefault();
        if(existingPerson != null)
        {
            ViewBag.firstName = existingPerson.FirstName;
            ViewBag.lastName = existingPerson.LastName;
            ViewBag.nickName = existingPerson.NickName;
            Session["pID"] = existingPerson.PersonID;
        }
        else
        {
            Session["nullExceptionMessage"] = $"Sorry the person you are looking for does not exist in the database";
            return RedirectToAction("Error");
        }
        return View();

    }

    [HttpPost]
    public ActionResult AddContactDetails(person p)
    {
        int a = (int)Session["pID"];
        PhonebookEntities db = new PhonebookEntities();
        person existingPerson = db.people.Where(x => x.PersonID == a).FirstOrDefault();
        existingPerson.NickName = Formatting.FirstCharToUpper(p.NickName);
        existingPerson.FirstName = Formatting.FirstCharToUpper(p.FirstName); 
        existingPerson.LastName = Formatting.FirstCharToUpper(p.LastName);           
        db.SaveChanges();

        return RedirectToAction("Index");
    }

查看

@using ThePhoneBook.ViewModel
@model CreateContactStepOne
@{
    ViewBag.Title = "The PhoneBook";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";
}

<br />
<div class="container-fluid">
    <div class="form-row align-items-center">
        
        <div class="col-6">
            <input type="text" id="SearchName" name="SearchName" class="form-control" placeholder="John Smith" />
        </div>
        <div class="col-2">
            <input type="submit" value="Search Contact" class="btn btn-outline-primary" />
        </div>
        <div class="col-4">
            <p>Validation Results</p>
        </div>
    </div>
    <div class="form-row">
        <div class="col">
            <br />
        </div>
    </div>

    
    <div class="form-row align-items-center">
        <div class="col border bg-light" >
            @using (Html.BeginForm("CreateContact", "Home", FormMethod.Post))
            {
                <div class="row">
                    <div class="col">
                        @Html.LabelFor(x => x.FirstName, new { @class = "font-weight-bold" })
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        @Html.TextBoxFor(x => x.FirstName, new { @class = "form-control", placeholder = "John" })
                    </div>
                </div>
                <div class="row">
                    <div class="col" @*style="font-size: 15px !important;"*@>                        
                        @Html.ValidationMessageFor(x => x.FirstName, "", new { @class = "text-danger"})
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        @Html.LabelFor(x => x.LastName, new { @class = "font-weight-bold" })
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        @Html.TextBoxFor(x => x.LastName, new { @class = "form-control", placeholder = "Smith"})
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        @Html.ValidationMessageFor(x => x.LastName, "", new { @class = "text-danger"})
                    </div>
                </div>
                <br />
                <div class="row">
                    <div class="col">
                        @Html.LabelFor(x => x.PhoneNumber, new { @class = "font-weight-bold"})
                         @Html.DropDownListFor(x => x.PhoneNumber, new SelectList(Enum.GetValues(typeof(Phone))), "Select Phone Type"@*, new { @class = "form-control"}*@)
                        @Html.ValidationMessageFor(x => x.PhoneNumber, "", new { @class = "text-danger"})
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        @*@Html.TextBoxFor(x => x.ContactPhoneNumber, new { @class = "form-control", placeholder = "717-123-4567"})*@
                        @Html.TextBoxFor(x => x.ContactPhoneNumber, htmlAttributes: new { @class = "form-control", id = "txtnumber", placeholder = "717-123-4567", maxlength = "12"})
                        @*<input class="form-control" id="txtnumber" name="ContactPhoneNumber" type="text" maxlength="12" placeholder="XXX-XXX-XXXX" />*@
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        @Html.ValidationMessageFor(x => x.ContactPhoneNumber, "", new { @class = "text-danger"})
                    </div>
                </div>
                <br />
                <div class="row">
                    <div class="col">
                        <input type="submit" value="Add Contact" class="btn btn-outline-primary" />&nbsp;
                        <a href="/Home/Index" class="btn btn-outline-primary">Cancel</a>
                        
                    </div>
                </div>  
                <br />
            }
        </div>
        
    </div>
    @*<div class="form-row align-items-center">
        <div class="col">
            <h1>Placeholder Text</h1>
        </div>
    </div>*@
</div>

if(!ModelState.IsValid)return View(contact); 添加到 CreateContact 操作

[HttpPost]
    public ActionResult CreateContact(CreateContactStepOne contact)
    {
            if(!ModelState.IsValid)return View(contact);
            person p = new person();
            p.FirstName = contact.FirstName;
            p.LastName = contact.LastName;

            if (contact.PhoneNumber == Phone.Home)
            {
                p.HomePhone = contact.ContactPhoneNumber.ToString();
            }
            else if (contact.PhoneNumber == Phone.Mobile)
            {
                p.MobilePhone = contact.ContactPhoneNumber.ToString();
            }
            else if (contact.PhoneNumber == Phone.Office)
            {
                p.OfficePhone = contact.ContactPhoneNumber.ToString();
            }

            PhonebookEntities db = new PhonebookEntities();

            db.people.Add(p);
            db.SaveChanges();
            //Redirect to ActionMethod ContactDetails and passes the personID as parameter
            return RedirectToAction("AddContactDetails", new { id = p.PersonID });

    }

您只需在 Home ControllerCreateContact 操作中添加 ModelState 验证

[HttpPost]
public ActionResult CreateContact(CreateContactStepOne contact)
{
        // add this section to the top of your action
        if(!ModelState.IsValid)
        {
           return View("viewName", contact);
        }



        person p = new person();
        p.FirstName = contact.FirstName;
        p.LastName = contact.LastName;

        if (contact.PhoneNumber == Phone.Home)
        {
            p.HomePhone = contact.ContactPhoneNumber.ToString();
        }
        else if (contact.PhoneNumber == Phone.Mobile)
        {
            p.MobilePhone = contact.ContactPhoneNumber.ToString();
        }
        else if (contact.PhoneNumber == Phone.Office)
        {
            p.OfficePhone = contact.ContactPhoneNumber.ToString();
        }

        PhonebookEntities db = new PhonebookEntities();

        db.people.Add(p);
        db.SaveChanges();
        //Redirect to ActionMethod ContactDetails and passes the personID as parameter
        return RedirectToAction("AddContactDetails", new { id = p.PersonID });

}