Friday, May 6, 2011

How to catch Non-integer values mapped to integer properties in UpdateModel()

Let's say you have an object called Person that looks like this:

class Person
{
  public int ID { get; set; }
  public string Name { get; set; }
  public int NumberOfCatsNamedEnder { get; set; }
}

I have a simple HTML form that exposes the properties that gets posted to an ASP.NET MVC action inside of my PersonController class. The issue I have is that if someone puts in the letter 'A' for NumberOfCatsNamedEnder, I get a The model of type 'Person' was not successfully updated. error. Since this happens while trying to update the Model, I can't find any way to check to see if someone passed in a non-integer value without resorting to

if(!IsInteger(formCollection["NumberOfCatsNamedEnder"]))
{
  ModelState.AddModelError(
    "NumberOfCatsNamedEnder",
    "Ender count should be a number");
}

Is there a better way to do this? I was able to find some information on custom ModelBinders; is that what is needed?

From stackoverflow
  • I really like the approach of using a presentation model. I'd create a class like this:

    class PersonPresentation
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string NumberOfCatsNamedEnder { get; set; }
    
        public void FromPerson(Person person){ /*Load data from person*/ }
    }
    

    Then your controller action can bind the view to a PersonPresentation:

    public ActionResult Index()
    {
        Person person = GetPerson();
        PersonPresentation presentation = new PersonPresentation();
        ViewData.Model = presentation.FromPerson(person);
        return View();
    }
    

    ...and then accept one in your Update method and perform validation:

    public ActionResult Update(PersonPresentation presentation)
    {
        if(!IsInteger(presentation.NumberOfCatsNamedEnder))
        {
            ModelState.AddModelError(
              "NumberOfCatsNamedEnder",
              "Ender count should be a number");
        }
        ...
    }
    

0 comments:

Post a Comment