[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")]CustomerInfo customerinfo)
{
if (customerinfo.FirstName.Trim().Length == 0)
ModelState.AddModelError("FirstName", "First name is required.");
if (customerinfo.LastName.Trim().Length == 0)
ModelState.AddModelError("LastName", "Last name is required.");
if (customerinfo.Phone.Length > 0 && !Regex.IsMatch(customerinfo.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
ModelState.AddModelError("Phone", "Invalid phone number.");
if (customerinfo.Email.Length > 0 && !Regex.IsMatch(customerinfo.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
ModelState.AddModelError("Email", "Invalid email address.");
if (!ModelState.IsValid)
return View();
try
{
BLL.Customer customer = new BLL.Customer();
customer.CreateCustomer(customerinfo);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
1 Answer
You should really step through and indicate where exactly it fails. Most likely this would tell you enough to fix the problem yourself. In particular, look at the line-number; that will take you to the line that is failing.
However, my guess is simply that one of FirstName, LastName, Phone or Email is null (which is the default for strings, so entirely expected) - or that customerinfo itself is null.
Changing to
if (customerinfo.FirstName == null || customerinfo.FirstName.Trim().Length == 0)
ModelState.AddModelError("FirstName", "First name is required.");
(etc) will probably fix it for you.
2 Comments
user754461
Thanks a lot the validation is Working now
blowdart
That check is what string.IsNullOrWhiteSpace) is for grin So you could simply with if (string.IsNullOrWhiteSpace(customerinfo.FirstName)) ModelState.AddModelError("FirstName", "First name is required.");
customerinfois null,so u r getting that exception..