整理好 Edit.aspx 试图后,应该考虑要为用户的输入增加验证。从数据模型可以获得部分支持。如果用户给某个数值类型的字段输入了字符串,他会看到一个错误页面,可能是默认的 ASP.NET 栈信息或者自定义错误页面(如果在控制器和应用程序中启用了自定义错误处理)。
绝大部分用户都不能够通过栈追踪信息知道自己输入了非法的值,并且他们也不应该知道,这就是为什么 MVC 框架内置了某些强大的验证功能。
执行基本的验证
MVC 框架使数据从客户端回发到控制器时的错误验证检查变得非常简单。我们修改了 Edit 方法获取用户数据的签名,这样 MVC 框架就会通过表单的值自动创建 ProductListWrapper 的实例。
通过 ModelState.IsValid 方法检查验证错误,如果有问题,及时从方法中返回,指定把传给 Edit 方法的 ProductListWrapper 实例使用 Edit 视图显示。要注意的是,这里再次把供应商和类别名作为视图数据的一部分,这是因为 Edit.aspx 依赖于这些数据来呈现,如果没有这些就会抛出一个异常:
int id, ProductListWrapper pwrap)
{
try
{
if (!ModelState.IsValid)
{
ViewData["categories"] = nwa.GetAllCategories();
ViewData["suppliers"] = nwa.GetAllSuppliers();
return View("Edit", pwrap);
}
Products prod = nwa.GetProduct(id);
if (prod != null)
{
ProductListWrapper wrapper = new ProductListWrapper()
{
product = prod
};
UpdateModel(wrapper);
prod.SupplierID = nwa.GetSupplierID(wrapper.SelectedSupplier);
prod.CategoryID = nwa.GetCategoryID(wrapper.SelectedCategory);
nwa.SaveChanges();
return RedirectToAction("Index");
}
else
{
throw new NoSuchRecordException();
}
}
catch
{
return View();
}
}