asp.net-mvc – ASP.NET MVC – ModelState.IsValid是false,如何绕过?

我有一个小应用程序,我在创建一个客户
[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateCustomer(GWCustomer customer)
{
    if (string.IsNullOrEmpty(customer.CustomerName))
    {
        ModelState.AddModelError("CustomerName","The name cannot be empty");
    }
    //...
    if (ModelState.IsValid)
    {
        //insert in db
    }
}

我的问题是GWCustomer对象有一个Id,它是主键,不能为null.这使得验证框架将其标记错误.但这不是一个错误,我还没有创建客户,现在应该是null,直到它被保存.我该如何绕过这个?还是解决它?

我永远不会在DB中插入它,因为ModelState永远不会有效.

编辑我正在使用Linq to sql和存储库模式.

解决方法

这将从绑定中排除值,但不会验证:
public ActionResult CreateCustomer([Bind(Exclude = "Id")]GWCustomer customer)

即使发生验证,您仍然可以通过调用以下方法来更正ModelState:

ModelState.Remove("Id");

如果只有Id导致错误,它将删除与Id相关的条目并将ModelState.Valid属性更改为true.

建议不要在视图层中使用数据层对象.您绝对应该考虑创建专用视图模型,而不使用Id字段.

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...