Monthly Archives: June 2016

Realtime MVC ModelState errors during debugging

While working on my most recent ASP.NET MVC project, I was having a tough time figuring out why my ModelState was invalid. It was due to the fact that I set the error messages to “Required” or “Invalid” for ALL of my model properties (to support the way the view presents the error messages). In retrospect, this probably wasn’t the smartest choice. Oh well, now I’m stuck figuring out another way to determine the properties causing Model validation to fail.

With Visual Studio 2015, I discovered a marvelous way to get the names of the properties with invalid values… buy using a watch! Watches now support lambda expressions (as long as there are no external dependencies, such as LINQ to SQL), so I thought… this would be a good time to test that functionality.

Since I was interested in the actual name of the property that was causing
ModelState.IsValid to return false, I used the following watch:

ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => x.Key).ToList()

For those who don’t usually use watches, you may not know that a watch can be created directly in the watch window by just typing it in! That is what you will need to do here, since I’m guessing that this value is most likely not in your code…

Untitled

If you get a message under Value saying “This expression causes side effects and will not be evaluated,” just click the refresh button to the right of the message to force-evaluate the watch. Once you do so, you’ll be able to expand the watch object to see your offenders!

Untitled

Pretty neat!

Advertisements