asp.net-mvc-2asp.net-mvc-2-validation

ViewModel not matching model causes modelstate to be invalid


I have a model class like this:

class Person {
   string FirstName, 
   string LastName,
   string ID
}

When I send the model to the browser via a GET, I send the data as a composite of two fields (e.g. FirstName.ToString() + LastName.ToString()) through an anonymous type.

The problem comes when I do a POST back to the server. Since the JSON is coming back as different from the model, it comes back as invalid through ModelState.IsValid() because my action method is expecting a List<Person> persons.

I really don't want to create a ModelViewModel duplicating code, because one field is causing the model to be invalid. Is there a way around this?


Solution

  • In this case, I would add DataAnnotations to the ViewModel class and change the Action to accept the ViewModel rather than the Model.

    Once you validate that the ViewModel being passed to the Action is valid, you can parse the composite field back to into the First and Last names properly.