Using jQuery form validation before Ajax submit in ASP.Net MVC

Last Reply one year ago By bahare

Posted one year ago

please see this link

https://www.aspsnippets.com/Articles/ASPNet-MVC-CRUD-Select-Insert-Edit-Update-and-Delete-in-ASPNet-MVC-Razor.aspx

the ajax create method is:

 

[HttpPost]
    public JsonResult InsertCustomer(Customer customer)
    {
        using (CustomersEntities entities = new CustomersEntities())
        {
            entities.Customers.Add(customer);
            entities.SaveChanges();
        }
 
        return Json(customer);
    }

 

and this is jquery.ajax add fuction:

  

//Add event handler.
        $("body").on("click", "#btnAdd", function () {
            var txtName = $("#txtName");
            var txtCountry = $("#txtCountry");
            $.ajax({
                type: "POST",
                url: "/Home/InsertCustomer",
                data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var row = $("#tblCustomers tr:last-child").clone(true);
                    AppendRow(row, r.CustomerId, r.Name, r.Country);
                    txtName.val("");
                    txtCountry.val("");
                }
            });
        });

and in view there's not any

 

how can validate both client side and server side errors and exceptions asp.net mvc way?

I mean in a normal form we had:

if (ModelState.IsValid) {}

in action method

and using jquery.validate.unobtrusive.js we could show validation error in

@Html.ValidationSummary

@Html.ValidationMessageFor

 

what about $.ajax crud validation?