Search code examples
c#jqueryajaxasp.net-mvcjquery-ajaxq

controller doesn't get hit by jquery ajax : asp.net mvc 5


I have the below form

<form class="regForm" id="frmRegistration" method="post">
<h3>Register Customer Patient</h3>
@Html.ValidationSummary(true)

@Html.LabelFor(m => m.LastName)
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control cfield", required = "required", autofocus = "autofocus" })
@Html.LabelFor(m => m.FirstName)
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control cfield", required = "required" })

@Html.LabelFor(m => m.MiddleName)
@Html.TextBoxFor(m => m.MiddleName, new { @class = "form-control cfield", required = "required" })
@Html.LabelFor(m => m.BirthDate)
@Html.TextBoxFor(m => m.BirthDate, new { @class = "form-control cfield", required = "required" })
@Html.LabelFor(m => m.Address)
@Html.TextBoxFor(m => m.Address, new { @class = "form-control cfield", required = "required" })
<button type="submit" id="btnSave" class="btnreg btn btn-primary form-control">REGISTER</button>
<button type="button" onclick="clearTexts();" class="btnClear btn btn-danger form-control">CLEAR</button>

Below is the controller action method which I want to trigger/call

 [HttpPost]
    public ActionResult AddCustomerPatient(Customer _Customer)
    {
        using (var db = new DCDBEntities())
        {
            db.Customers.Add(_Customer);
            db.SaveChanges();
        }

        return  Json(new {registeredCustomer="ok"});

    }

Below is my jquery ajax which doesn't work

  $("#btnSave").click(function () {
            e.preventDefault();
            var PotentialCustomer = {

                "LastName": 'A',
                "FirstName": 'A',
                "MiddleName": 'A',
                "BirthDate": 'A',
                "Address": 'A'

            };


            $.ajax({
                type: 'POST',
                url: '/Registration/AddCustomerPatient',
                data: 'JSON.stringify(PotentialCustomer),',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (response) {
                    alert("Successfully Registered Customer/Patient!");

                }
            });
        });

Problem 1.) The controller action method is not getting hit ( I placed a breakpoint)

Problem 2.) How can I pass the Model to the controller action method and save it via linq to entities.

I've been searching and tried a lot but still not able to get it done.

Below is the routconfig

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

I tried to put a breakpoint in the GET or first method of my controller , whenever I click the "REGISTER" button it gets hit and not the [HttpPost] , why is that?

  public ActionResult RegisterCustomerPatient()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AddCustomerPatient(Customer _Customer)
    {
        using (var db = new DCDBEntities())
        {
            db.Customers.Add(_Customer);
            db.SaveChanges();
        }

        return  Json(new {registeredCustomer="ok"});

    }

do i need to create a view for HTTPPOST action method?


Solution

  • your ajax request should be like this

     $("#btnSave").click(function (e) { //added e
                e.preventDefault();
                var _Customer= {     //changed the name to name of parameter of action
    
                    "LastName": $("#LastName").val(),
                    "FirstName": $("#FirstName").val(),
                    "MiddleName": $("#MiddleName").val(),
                    "BirthDate": $("#BirthDate").val(),
                    "Address": $("#Address").val()
    
                };
    
    
                $.ajax({
                    type: 'POST',
                    url: '/Registration/AddCustomerPatient',
                    data: JSON.stringify(_Customer),    //removed '' and corrected the format
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    success: function (response) {
                        alert("Successfully Registered Customer/Patient!");
    
                    }
                });
            });
    

    JSON.stringify is a function so it should not be placed inside '' and JSON.stringify(_Customer) object name should match the name of parameter of Action which is Customer _Customer and also you used e.preventDefault(); without adding e in parameter