加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:02:02 所属栏目:asp.Net 来源:网络整理
导读:我有一个小应用程序,我在创建一个客户 [Authorize][AcceptVerbs(HttpVerbs.Post)]public ActionResult CreateCustomer(GWCustomer customer){ if (string.IsNullOrEmpty(customer.CustomerName)) { ModelState.AddModelError("CustomerName","The name canno
我有一个小应用程序,我在创建一个客户
[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字段.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读