How to reuse model metadata for custom view models?

I am working on an ASP.NET MVC 2 project with some business objects that apply data metadata data attributes (validation attributes, display attributes, etc.) to them.

Sort of:

//User entity public class User { [DisplayName("Vorname")] [Required(ErrorMessage = "Vorname fehlt")] [StringLength(MaxNameLength, ErrorMessage = "Vorname ist zu lang")] public string FirstName { get; set; } [DisplayName("Nachname")] [Required(ErrorMessage = "Nachnamefehlt")] [StringLength(MaxNameLength, ErrorMessage = "Nachname ist zu lang")] public string LastName { get; set; } [Required] public string Password{ get; set; } } 

Using metadata from different views is not a problem if I use my business entities as view modes or as part of such a view model:

 //custom viewmodel with a user entity public class CustomViewModel { public User{get;set;} //some more properties... } 

However, sometimes I need to encode a view to edit some, but not all fields of an object. For these fields, I want to reuse the metadata already specified in my user entity. The remaining fields should be ignored. I am talking about custom view models, such as:

 [MetadataType(typeof(User))] public class UserNameViewModel { public string FirstName { get; set; } public string LastName { get; set; } //no password on purpose, the user should only //edit his first and last name in this view } 

Where I ran into problems. The user view model above throws an exception when a view is created because it does not have a password property.

The associated metadata type for the type 'Zeiterfassung.Models.ViewModels.Users.UserNameViewModel + UserModel' contains the following unknown properties or fields: Password. Please make sure that the names of these members match the names of the properties on the main type.

In addition, even if this exception did not occur, I expect to get even more problems with checking the model when submitting the form, because the Password is marked as required in my business entity.

I can come up with a few workarounds, but no one seems really perfect. In any case, I cannot change the database layout so that the password field is in a separate object in my example above.

How would you handle this scenario?

+4
source share
1 answer

The only recommendation I can give you is to have view models specific to each view and to have only the necessary properties and validation attributes on these view models. Do not worry if you repeat some validation attributes and properties on view models. What they are for: reflect the logic of this view.

0
source

All Articles