Bypass client side validation mvc 3
This is the model which we are using...
Public Class Person
{
[Display(ResourceType = typeof(BasicTags), Name = "FirstName")]
[Required(ErrorMessageResourceName = "FirstNameRequired", ErrorMessageResourceType = typeof(BasicErrors))]
public string FirstName;
[Display(ResourceType = typeof(BasicTags), Name = "LastName")]
[Required(ErrorMessageResourceName = "LastNameRequired", ErrorMessageResourceType = typeof(BasicErrors))]
public string LastName;
}
Both the fields are set as required true. Now we have another developer using this same Model in another view, he doesn`t want this validation for his page, how to skip the validation in the server s开发者_如何学JAVAide and before saving?
The database fields are set as allow null.
ViewData.ModelState.Remove("FirstName")
ViewData.ModelState.Remove("LastName")
This only removes the client side message but the actual validation still remains. Is there any way, so that I can save.
Thanks.
You should make a custom View Model that has these properties but doesn't have their validation annotations for that specific page.
Simply don't check ModelState.IsValid on the server side and save your data.
HOWEVER - I would just make a copy of that view model, remove your attributes and be done with it. A ViewModel is for a View - if you have a different view, the standard thing to do is create a new Model. However - its your app - so the solution to do what you wanted is above.
If you are worried about the client side validation, then you have to create your own handler for the submit function and don't check if its valid - just post. Another hack. So - again.. try not to do it this way. : )
You can also call ModelState.Remove("FirstName");
Before ModelState.IsValid
and it will do the trick, Like
ModelState.Remove("FirstName");
if(ModelState.IsValid){
// your code
}
精彩评论