0

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?

6
  • 1
    First, it needs to be $("#btnSave").click(function (e) { so e.preventDefault() works (although it really should be $('#frmRegistration').submit(... And all it needs to be is data: $('#frmRegistration').serialize(), and delete the contentType option Commented Mar 21, 2017 at 10:30
  • @StephenMuecke , Still not working . . . . Commented Mar 21, 2017 at 10:37
  • Then what errors are you getting in the browser console? Commented Mar 21, 2017 at 10:45
  • I got a different error now, when I click the REGISTER button the url in the browser is this localhost:51084/Registration/RegisterCustomerPatient, and that is not the action method i have specified in jquery ajax function why it is redirecting to that ? Commented Mar 21, 2017 at 11:03
  • Because you have not done what I said in the first comment - function (e), not function () Commented Mar 21, 2017 at 11:05

6 Answers 6

1
 var formData = $('#frmRegistration').serialize();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("AddCustomerPatient", "Registration")',
            data: formData,
            success: function (response) {
                alert("Successfully Registered Customer/Patient!");
             }
         });

better to serialize the form data and send it to controller action method

Sign up to request clarification or add additional context in comments.

2 Comments

<form class="regForm" id="frmRegistration" method="post"> instead this one use MVC Razor engine form @{Html.BeginForm("AddCustomerPatient", "Registration", FormMethod.Post)}; and don't write any jquery save click event
I already achieved that, what I want to try is the jquery ajax
1

data: 'JSON.stringify(PotentialCustomer),'

Please remove single quotes . It will be fine data: JSON.stringify(PotentialCustomer),

6 Comments

just a string, I got a different error now, when I click the REGISTER button the url in the browser is this localhost:51084/Registration/RegisterCustomerPatient, and that is not the action method i have specified in jquery ajax function why it is redirecting to that ?
please share view page
the view is in the above post. "form"
Ok .Did you add Html.Begin in View page
Did you check weather the click event is working or not using an alert.
|
1

Problem is line

 data: 'JSON.stringify(PotentialCustomer),',

and

 click(function () {
 // e is undefined here. Add e as parameter in function.
    e.preventDefault();

JSON.stringify should be used as funtion not string. In above it is used as string. Change it to following (assuming all fields are string in model)

$("#btnSave").click(function (e) {
        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!");

            }
        });

4 Comments

tried it but not working, it's not hitting the breakpoint in controller action
Could you please cross check route configuration? If url format is correct "/Registration/AddCustomerPatient". Also, please update question with controller class and route configuration.
Hi please see above routeconfig. Not sure what to do with that
I tried running your code, it gives error on e.preventDefault(); I have updated answer with fixed version
1

there is a , inside data

data: 'JSON.stringify(PotentialCustomer),',

next am not sure but try

data:{'_customer':'PotentialCustomer'}; instead of data.strinify

Comments

1

Problem 1.) The controller action method is not getting hit

I think it is caused by wrong URL of ajax post. You could try to open Network tab of Developer Tool on Browser to confirm that. It you ajax post return HTTP status 404, you should update the URL of your ajax post.
One way to get correct URL is using the @Url.Action to add URL attribute of your submit button.

<button type='button' id='btnSave' data-url='@Url.Action("AddCustomerPatient", "Registration")' class='btnreg btn btn-primary form-control'>REGISTER</button>

Then you could get this value inside click function like this

$("#btnSave").data('url')

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

After getting correct URL, you should update your click function

$("#btnSave").click(function () {
    var formData = $('#frmRegistration').serialize();
    $.ajax({
        type: 'POST',
        url: $("#btnSave").data('url'),
        data: formData,
        success: function (response) {
            alert("Successfully Registered Customer/Patient!");
         }
     });
 });

Alternative method
I guess you want to make an ajax post instead of submit form, so you could try another simple method as below.

The razor code

@using (Html.BeginForm("AddCustomerPatient", "Registration", FormMethod.Post, new { id = "frmRegistration"))
{
    ...
    <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>   
}

The script

$(function () {
    $("#frmRegistration").on('submit', function (e) {

        e.preventDefault(); // prevent the form's normal submission

        var $form = $(this);
        var dataToPost = $form.serialize();

        $.post($form.attr('action'), dataToPost)
            .done(function(response, status, jqxhr){ 
                // this is the "success" callback
            })
            .fail(function(jqxhr, status, error){ 
                // this is the ""error"" callback
            });
    })
})

Comments

0

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

14 Comments

what is the difference you've made?
thanks! I got a different error now, when I click the REGISTER button the url in the browser is this localhost:51084/Registration/RegisterCustomerPatient, and that is not the action method i have specified in jquery ajax function why it is redirecting to that ?
did you remove e.prevent default? because it seems like it is submitting the to default action and also did you place a breakpoint to check is it hitting the action ? @FrancisSaul
@FrancisSaul and remove type="submit" you dont need this since you are using ajax
already remove the type="submit" and the e.prevenDefault but i got a a different action method in the address bar it's the RegisterCustomerPatient and not the AddCustomerPatient method
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.