tags:

views:

35

answers:

1

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.

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
}

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

A: 

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