我不了解ModelState.IsValid
,我相信这是CreateContact
Action方法中所缺少的。请解释,我应该如何检查If(ModelState.IsValid)?我的验证无效。
如果文本框(或模型属性)为null
,我应该看到一条错误消息。如果它符合验证规则,那么我应该能够将日期保存到数据库中,并在单击AddContactDetails
按钮时重定向到submit
操作方法。
查看模型
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
}
HomeController
[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" />
<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>
答案 0 :(得分:0)
将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 });
}
答案 1 :(得分:0)
您只需要在 CreateContact 操作的 Home Controller 中添加 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 });
}