Question

I have a simple form that posts a ViewModel to an Action method. Before saving the information the ModelState is checked with a standard if(ModelState.IsValid). Then a new object is created and saved. Great, it works.

Recently another dev went in and created a new view with my original ViewModel. He also added a new [Required] property to the ViewModel to make his logic work.

By doing that his logic broke my initial logic. Because my initial view doesn't use his new Required property so ModelState.IsValid check now fails and my code doesn't run.

What is the best approach to take here ? Though I don't want to but should I get rid of ModelState.IsValid check on my Post actions or can I somehow flag his new property to Not be required when used in my original views or when being posted in my action method ?

Thank you in advance.

Was it helpful?

Solution

You can use attribute [Bind(Exclude="")] in your action method like below. Then, when you submit the form, model binder will ignore that property even it is required.

[HttpPost]
public ActionResult Index([Bind(Exclude = "AdditionalProperty")]YourModel model)
{
  //
}

OTHER TIPS

You can derive the model from IValidatableObject, and then perform your own custom validations using

public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
}

How do I use IValidatableObject?

Edtied to add: If it were me, it would seem to make more sense to have him create an inherited model from your model, even if it only has 1 property in it. This would keep the native MVC validations working correctly with minimal effort on your part.

you have two choice(to the best of my knowledge!), first you can unbind the that required property while posting it to the action:

    [HttpPost]
    public ActionResult Create([Bind(Exclude = "RequiredProperty")]MyViewModel myViewModel)
    {
       if(ModelState.IsValid)
       {
         //
       }

    }

but you can solve this issue for your application by mapping the ViewModel to View in your get action, and send it to the view. try this great article

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top