I need to validate data from client side and server side in my project . I use ajax to validate client side data but i have certains statements inside (model.isvalid) . so i need to post data on button click also . Becasue of this the data is getting inserted 2 times intead of 1. I can understand that i am passing same data twice to the controller one via ajax call and one on form post method
I can not remove the ajax call since my org is asking for a client side validation . How to resolve this error
My view is as follows
````
````
I am using jQuery now to validate the entire form by placing if for the form tag on the client side and my jQuery is as follows.````
````
my model is as follows````
public partial class EmployeeBasicInformation
{
public int EmployeeId { get; set; }
[Required]
[ValidPrefix(ErrorMessage =
"Prefix can not be epmty")]
public int? EmployeePrefix { get; set; }
[RegularExpression(@"^[a-zA-Z\s\.\']+$", ErrorMessage = "Please enter a valid First name")]
public string? EmployeeFirstName { get; set; }
[RegularExpression(@"^[a-zA-Z\s\.\']+$", ErrorMessage = "Please enter a valid last name")]
public string? EmployeeLastName { get; set; }
[ValidGender(ErrorMessage =
"Gender can not be epmty")]
public int? EmployeeGender { get; set; }
[Validmaritalstatus(ErrorMessage =
"MaritalStatus can not be epmty")]
public int? EmployeeMaritalStatus { get; set; }
````
inside model i have custom validation for dropdown which is not getting validated on client side validation
my controller is as follows
````
public partial class EmployeeBasicInformation
{
public int EmployeeId { get; set; }
[Required]
[ValidPrefix(ErrorMessage =
"Prefix can not be epmty")]
public int? EmployeePrefix { get; set; }
[RegularExpression(@"^[a-zA-Z\s\.\']+$", ErrorMessage = "Please enter a valid First name")]
public string? EmployeeFirstName { get; set; }
[RegularExpression(@"^[a-zA-Z\s\.\']+$", ErrorMessage = "Please enter a valid last name")]
public string? EmployeeLastName { get; set; }
[ValidGender(ErrorMessage =
"Gender can not be epmty")]
public int? EmployeeGender { get; set; }
[Validmaritalstatus(ErrorMessage =
"MaritalStatus can not be epmty")]
public int? EmployeeMaritalStatus { get; set; }
}}}
````
How to resolve this
Naimish MakwanaPosted Feb 28, 2023, 3:56 PM
Hello Kaushik,
To avoid inserting data twice, You can disable the form's default submission behavior when the submit button is clicked. You can do this by adding
event.preventDefault();at the beginning of thesavecanditateinfofunction:Then, add
savecanditateinfo(event)as theonclickevent for the submit button, passing theeventparameter to the function:This way, the form data will be submitted only once, via the AJAX call, and not via the default form submission behavior.
Thanks
Naimish Makwana