0
[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();
    }
}
3
  • 1
    customerinfo is null,so u r getting that exception.. Commented May 29, 2011 at 9:04
  • Have you seen the Data Annotation Validation Attributes? - msdn.microsoft.com/en-us/library/ee256141.aspx This looks like a perfect use case for them Commented May 29, 2011 at 9:05
  • also Data Annotation Validation Attributes not worked! Commented May 29, 2011 at 9:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot the validation is Working now
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.");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.