user1765862
user1765862

Reputation: 14165

How to intentionally step into ModelStateError when posted model is Ok inside debugging?

If my model has properties like:

public int Id { get; set; }

public string Code { get; set; }

public int Age { get; set; }

and on HTTP POST method I'm receiving this object:

[HttpPost]
public ActionResult Edit(MyModel model)
{
   if (ModelState.IsValid)
   {

   }
   else
   {
      // how to get here?
   }
}

I want to reproduce scenario when posted model has errors. How can I do that inside debugging?

Upvotes: 1

Views: 27

Answers (2)

Jason Evans
Jason Evans

Reputation: 29186

You can manually add errors into the model state using AddModelError.

ModelState.AddModelError("MyError", "This is the error message");

I sometimes do this if I want to force an error, in order to test some validation messages in views without having to set up the precise state of the data in order to get it invalid.

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 157058

If you don't want to change the code: set a break point at if (ModelState.IsValid) and drag the next statement indicator (the yellow arrow) to the else branch.

Upvotes: 4

Related Questions