1

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.

4
  • 4
    it sounds like you're keying off of whether or not the password is provided to determine what action to take. Just allow the password to be provided either way and use something else to determine which action to take Commented Dec 1, 2014 at 14:26
  • @DLeh I'm not sure how could I achieve it other way. The way I imagined this scenario is to enter password in Create where it is required. In the Edit action password doesn't get displayed at all and in case user enters it it means he is changing it. Commented Dec 1, 2014 at 14:45
  • you'd have to provide more info about your situation as well as some code for me to provide any more help Commented Dec 1, 2014 at 14:46
  • @DLeh Thank you for the initiative but as this is the simplest possible scenario I don't think I need to cope anything more complicated then simply leaving out the property. Commented Dec 1, 2014 at 14:48

2 Answers 2

2

Use:

if (string.IsNullOrEmpty(model.Password))
{
    ModelState.Remove("Password");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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
}

1 Comment

Removing [Required] is a great addition to the code! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.