问题描述
||
[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();
}
}
解决方法
您应该真正地逐步完成并指出确切的失败之处。这很可能会告诉您足够的信息来自己解决问题。特别要看的是行号。那将带您进入失败的生产线。
但是,我的猜测很简单,
FirstName
,LastName
,Phone
或Email
之一是null
(这是字符串的默认值,因此完全可以预期)-customerinfo
本身为空。
更改为
if (customerinfo.FirstName == null || customerinfo.FirstName.Trim().Length == 0)
ModelState.AddModelError(\"FirstName\",\"First name is required.\");
(etc)可能会为您修复它。