Saturday, June 13, 2009

ASP.NET MVC Form Validation Error with Decimal Parsing

Today I tried to put a relatively simple form together and was hoping to be done in a few minutes. Included on the form is an optional field asking for a monetary value. The type in the database is money and using LINQ-to-SQL the type is represented as a decimal.

All was well until the user entered a value that decimals generally don’t like to be converted into. Let’s assume ‘aaa’ for the time being. The result I was greeted with was this:

The model of type 'Foo' was not successfully updated.

My desire for ASP.NET MVC to handle this for me and put a nice validation message into the ModelState was just not happening.

My original code did this:

Foo foo = _modelRepository.FindFoo(id);
UpdateModel(foo);
The relatively simple fix is:
Foo foo = _modelRepository.FindFoo(id);
UpdateModel(foo, "SomeStringField", "SomeOtherStringField");

if (!TryUpdateModel(foo, "TheDecimalField"))
{
ModelState.AddModelError("TheDecimalField", "Does that look like a number to you?");
}

5 comments:

  1. This is a nice article..
    Its easy to understand ..
    And this article is using to learn something about it..

    c#, dot.net, php tutorial, Ms sql server

    Thanks a lot..!
    ri70

    ReplyDelete
  2. Thanks for sharing! It's good to find a food that we can actually feed dogs.
    Buy Beef Ears

    ReplyDelete
  3. Thank you for your articles that you have shared with us. Hopefully you can give the article a good benefit to us.
    Buy Beef Ears

    ReplyDelete
  4. How to get to Las Vegas Strip with Uber - DrMCD
    Directions to Golden งานออนไลน์ Nugget 양주 출장마사지 Las Vegas 순천 출장안마 (Paradise) with public transportation. The following transit lines have routes that 광양 출장샵 pass near 파주 출장마사지 Golden Nugget

    ReplyDelete
  5. Casino – Odds, Tips, Stats, & Reviews - Airjordan21
    The Casino 바카라 사이트 casinopan1xbet 먹튀 Odds, Tips, Stats, & Reviews - Airjordan21. Search to find your perfect balance of Air Jordan 12 retro events, bonuses and super air jordan 7 retro promotions in your inbox. make retro jordans

    ReplyDelete