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
IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.
Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5. Web API controllers don't have to check ModelState. IsValid if they have the [ApiController] attribute.
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 }
I'm using the ASP.NET Core 1.0.0 and async binding and for me the solution was to use ModelState.Remove and pass the property name (without object name).
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Submit([Bind("AerodromeID,ObservationTimestamp,RawObservation")] WeatherObservation weatherObservation) { weatherObservation.SubmitterID = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; weatherObservation.RecordTimestamp = DateTime.Now; ModelState.Remove("SubmitterID"); if (ModelState.IsValid) { _context.Add(weatherObservation); await _context.SaveChangesAsync(); return RedirectToAction("Index", "Aerodrome"); } return View(weatherObservation); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With