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

asp.net-mvc – 更新我的模型然后重新评估IsValid?

发布时间:2020-12-16 00:20:44 所属栏目:asp.Net 来源:网络整理
导读:我将一些值传递给我的控制器动作,一切都很好。 POST设计中将缺少两个属性。 然后我设置了缺失的值,但后来我想验证模型,它仍然是假的,因为看起来ModelState没有赶上我的更改。 [HttpPost,Authorize]public ActionResult Thread(int id,string groupSlug,C
我将一些值传递给我的控制器动作,一切都很好。 POST设计中将缺少两个属性。

然后我设置了缺失的值,但后来我想验证模型,它仍然是假的,因为看起来ModelState没有赶上我的更改。

[HttpPost,Authorize]
public ActionResult Thread(int id,string groupSlug,Comment comment,string submitButton)
{
  comment.UserID = UserService.UID;
  comment.IP = Request.UserHostAddress;
  UpdateModel(comment); //throws invalidoperationexception
  if (ModelState.IsValid) // returns false if i skip last line
  {
    //save and stuff
    //redirect
  }
  //return view
}

什么是最简洁的方法来轻拍模型状态并告诉它一切都会好的同时仍然验证从用户的POST绑定的所有其他内容

解决方法

如果模型需要缺少的值,但在绑定之后才会提供,则可能需要清除ModelState中这两个值导致的错误。
[HttpPost,string submitButton)
{
  comment.UserID = UserService.UID;
  comment.IP = Request.UserHostAddress;

  //add these two lines
  ModelState["comment.UserID"].Errors.Clear();
  ModelState["comment.IP"].Errors.Clear();

  UpdateModel(comment); //throws invalidoperationexception
  if (ModelState.IsValid) // returns false if i skip last line
  {
    //save and stuff
    //redirect
  }
  //return view
}

(编辑:李大同)

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

    推荐文章
      热点阅读