我将一些值传递给我的控制器动作,一切都很好。 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绑定的所有其他内容
@H_404_8@解决方法
如果模型需要缺少的值,但在绑定之后才会提供,则可能需要清除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 }@H_404_8@ @H_404_8@