Reputation: 2842
I am creating a web application using MVC 4.
I have a few properties in my view model that has been decorated with the required attribute as shown,
[Required(ErrorMessageResourceName = "StateRequiredMessage", ErrorMessageResourceType = typeof(Resources.Agency.CreateEdit))]
public int? PostalAddressStateId { get; set; }
but then in my view, depending on what the user selects from a tick box, I disable some of the properties that have been tagged as required.
I disable the controls using jQuery:
$("#PostalAddressStateId").attr("disabled", true);
Then when I try to save, it says the value is required. How do I solve this?
Upvotes: 1
Views: 7341
Reputation: 1295
Try
ModelState.Remove("PostalAddressStateId");
at your controller
Upvotes: 3
Reputation: 1601
Try this:
PostalAddressStateId.Attributes.Remove("Required");
You might need to set a boolean in javascript and send it back to the controller, the required attribute impacts your server side code as well.
In my opinion, a field like this shouldn't be marked as required unless it's always required. If this is in a viewmodel, then I'd probably remove the attribute and replace it with a custom attribute or some other way of determining that it's filled in when it must be and not filled in when it's not required.
More about attributecollections here:
http://msdn.microsoft.com/en-us/library/system.web.ui.attributecollection.remove(v=vs.110).aspx
Upvotes: 1
Reputation: 977
I would check out MVC Foolproof Validation on CodePlex. You could use the RequiredIfTrue attribute that comes with Foolproof to solve the issue above.
http://foolproof.codeplex.com/
Upvotes: 0