更新我的模型,然后重新评估IsValid? [英] Updating my model then re-evaluate IsValid?

查看:66
本文介绍了更新我的模型,然后重新评估IsValid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些值传递给我的控制器操作,并且一切正常.按设计,POST表单中将缺少两个属性.

I'm passing in some values to my controller action and everything is binding up fine. There will be two properties missing from the form POST by design.

然后我设置缺少的值,但是然后我想验证模型,并且它仍然说是false,因为看起来好像ModelState没有赶上我的更改.

I am then setting the missing values but then I want to validate the model and it is still saying false since it looks like the ModelState hasn't caught up with my changes.

[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
}

拍打ModelState并告诉它一切都会好的同时仍然验证用户POST绑定的其他所有内容的最干净的方法是什么

What is the cleanest way to pat the ModelState on the head and tell it that everything will be okay whilst still validating everything else that was bound from the user's POST

推荐答案

如果模型需要缺少值,但在绑定后才提供缺少的值,则可能需要清除.

If the missing Values are required for your model but will not be provided until after binding you may need to clear the errors caused by those two values from the ModelState.

[HttpPost, Authorize]
public ActionResult Thread(int id, string groupSlug, Comment comment, 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
}

这篇关于更新我的模型,然后重新评估IsValid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆