Reputation: 3720
I know that I can exclude or include bind on property via Bind attribute, but I'm not sure if I can do that programmatically (without creating separate ViewModel). The reason I'd like to achieve this is because I have a password field which should be included only in case the user has entered value in its field.
Upvotes: 1
Views: 289
Reputation: 733
Make the Password property in the viewModel optional, in other words don't annotate with required. In general all other validations (except for RequiredAttribute) pass when value is empty/null.
class MyViewModel
{
[MinLength(6)]
[HasUpper(1)]
[HasLower(1)]
// [Required] remove this line
public String Password { get; set; }
}
then in your controller action test if Password property is null or empty
if (!String.IsNullOrEmpty(model.Password))
{
// the user has entered value in its field
}
Upvotes: 2
Reputation: 20033
Use:
if (string.IsNullOrEmpty(model.Password))
{
ModelState.Remove("Password");
}
Upvotes: 2