Obsivus
Obsivus

Reputation: 8359

Jquery validation in MVC causing problems

I am using MVC-View Model, EF Model first

I am having problems with two of my Properties inside my View Model which is following:

[Required]
public string TeamName { get; set; }
[Required]
public string ConsultantName { get; set; }

These two properties can get disabled depending on what SubjectTypeName the user choose

 [Required]
 public string SubjectTypeName { get; set; }

Lets say I choose a SubjectTypeName Value and my TeamName and ConsultantName gets disabled, but when I want to save the form I get error beacuse my ModelState.IsValid gets false. And its the [Required] that makes it "false".

Is there any easy solutions for this? Like a easy Jquery code to inactive TeamName and ConsultantName from the validation so my ModelState.IsValid becomes "true"?

Thanks in Advance!

Upvotes: 0

Views: 192

Answers (3)

Malevolence
Malevolence

Reputation: 1857

Instead of marking those 2 properties as required (since they aren't in some cases), I would implement the IValidatableObject interface where you can implement this type of business logic trivially by comparing the values of several properties.

ScottGu has a blog post on exactly how to do this:

http://weblogs.asp.net/scottgu/archive/2010/12/10/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3.aspx

Upvotes: 0

pollirrata
pollirrata

Reputation: 5286

If the problem were on the client side, jQuery validate will display it. Your problem is on the validation of the server side, as you say, when the ModelState.IsValid is checked. What you will need to do is use CustomValidations for achieve what you need.

You may want to check this out

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You may take a look at the following blog post which illustrates how you could write a custom [RequiredIf] validation attribute that will handle conditional validation on the server and on the client. You can directly download the Mvc.ValidationToolkit which contains this validation attribute.

Upvotes: 1

Related Questions