How to handle model validation when the bound edit model != view model

137 views Asked by At

I have a situation in ASP.NET MVC 2 where I have a form whose fields are based on info supplied by a view model, but whose posted data is a subset of that data represented by a slimmer edit model. I'd like to add simple data annotation validation to the edit model, but since the view is based on the view model, I'm not sure how to proceed.

1

There are 1 answers

0
Robert Koritnik On BEST ANSWER

View model and controller action parameters don't have to be the same.

In your case this means that you may be using a richer model class to generate your view (and maybe even posting more information than needed) but your controller action would only use some information from that posted data to populate a simpler application model object instance. No problem. As long as field naming will suffice to populate properties correctly.

You may have these two classes:

public class User
{
    [Required]
    public string Username { get; set; }

    [Required]
    public string Password { get; set; }
}

public class Person: User
{
    public string Name { get; set; }

    public string Address { get; set; }
}

and then your view would be using Person and your controller action would have a parameter of type User. Fine. It will work.

There's no need for these classes to inherit each other either. I've just made it so in this simple example because this way they both share common property names. But otherwise they don't have to be related in any way shape or form as long as posted field names will be able to model bind to controller action parameter class properties.