views:

61

answers:

1

I'm currently using DataAnnotations to validate my MVC 2 app. However, I've ran into a small problem.

I currently have an object of type User which has a number of properties. All of which are required.

public class User
    {

        [Required(ErrorMessage = "Username is required")]
        public string Username { get; set; }

        [Required(ErrorMessage = "Password is required")]
        public string Password { get; set; }

        [Required(ErrorMessage = "Email is required")]
        public string Email { get; set; }

        [Required(ErrorMessage = "First name is required")]
        public string Firstname { get; set; }

        [Required(ErrorMessage = "Last name is required")]
        public string Lastname { get; set; }


    }

At signup, these are all mapped using the modelbinder and everything works great. However, on the "edit my detail" page only Firstname, Lastname and Email can be updated. Whenever the view posts back and modelbinding is applied I'm getting an alert Username/Password is a required field. Even though it is not required at this point. I've thought of two ways to get around this neither of which I feel are suitable (but may be wrong)

1: Create a custom viewmodel. This will work fine, but data annotations will need to be applied to this viewmodel meaning duplicate validation on the model and the user object.

2: Include all the fields in the renderd view and post them back. This has security risks, seems really messy and wouldn't scale well to complex viewmodels.

Can anyone recommend a best practice for this situation?

+1  A: 

There was similar question recently: http://stackoverflow.com/questions/2902951/needing-to-copy-properties-before-validation/2902987#2902987. In response I have suggested creating custom ModelBinder for usage only in this particular action, and I still believe it's a best solution.

tpeczek
Thanks for the link @tpeczek. Your solution is a good option however I've descided to go for the 1:1 View:ViewModel setup after reading Jimmy Bogard's post on http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx .
WDuffy