My current web project has an administration interface, in which the details of a user can be edited (not really revolutionizing, I admit...). The view uses a strongly typed model of a user, with validation attributes:
public class UserPrototype
{
[Required]
[StringLength(50, MinimumLength = 4)]
public string Username { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string FirstName { get; set; }
[Required]
[StringLength(50, MinimumLength = 1]
public string LastName { get; set; }
[Required]
[StringLength(250, MinimumLength = 6]
public string Password { get; set; }
/*
And so on
*/
}
When the user is updated, I would like to only update in the database those fields that have actually changed. The main reason is the password field - the password is of course stored as a hash, so when the user is retieved for editing there is nothing meaningful to display in that field. But the model binder validation requires a valid password.
So, can I still use the same class, but somehow only validate those fields that are submitted as changed (this I can accomplish though javascript)? I would like to avoid duplicating the UserPrototype class just to remove the Required attributes.
Use inheritance, this way you don't have to duplicate.
public class BaseUserPrototype
{
[Required]
[StringLength(50, MinimumLength = 4)]
public string Username { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string FirstName { get; set; }
[Required]
[StringLength(50, MinimumLength = 1]
public string LastName { get; set; }
/*
And so on
*/
}
public class NewUserPrototype: BaseUserPrototype
{
[Required]
[StringLength(250, MinimumLength = 6]
public string Password { get; set; }
/*
And so on
*/
}
public class EditUserPrototype: BaseUserPrototype
{
[StringLength(250, MinimumLength = 6]
public string Password { get; set; }
/*
And so on
*/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With