Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating my model then re-evaluate IsValid?

Tags:

asp.net-mvc

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

like image 573
BritishDeveloper Avatar asked Aug 02 '10 15:08

BritishDeveloper


People also ask

What causes false IsValid ModelState?

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.

Does Model validation occurs after model binding?

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.


2 Answers

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 } 
like image 80
KP. Avatar answered Oct 16 '22 14:10

KP.


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); } 
like image 31
Edward Comeau Avatar answered Oct 16 '22 16:10

Edward Comeau