为什么ajax没有将数据发布到控制器?

时间:2018-04-04 12:24:33

标签: javascript jquery asp.net ajax asp.net-mvc

我一直在尝试使用ajax将数据发送到控制器,但它会将我重定向到另一个网址,而不是将数据发布到控制器中。

@section CustomScripts
            {
    <script type="text/javascript">

        function save() {
            var BookingDetails =
            {
                VehicleModel: document.getElementById('VehicleModel').value,
                VehicleRegNo: document.getElementById('VehicleRegNo').value,
                AppointmentTime: '1',
                CustomerName: document.getElementById('CustomerName').value,
                ContactNo: document.getElementById('ContactNo').value
            }

            var bd = JSON.stringify(BookingDetails);

            $.ajax
            ({
                url: '@Url.Action("Appointment", "AddAppointment")',
                type: 'POST',
                contentType: "application/json; charset= utf-8",
                data: bd,
                dataType: 'json',
                success: function (results) {

                    @*window.location = '@Url.Action("Appointment", "AddAppointment")';*@

                }
            });
        }



    </script>
}

控制器:

 [HttpPost]
        public ActionResult AddAppointment(AddBookingsViewModel AddBookingVM)
        {
            BookingsRepository BookingRep = new BookingsRepository();

            int ReturnRowsCount = BookingRep.InsertCustomerAppointments(AddBookingVM, out ReturnStatus, out ReturnMessage);

            if (ReturnRowsCount > 0)
            {
                //ShowMessage(MessageBox.Success, OperationType.Saved, ReturnMessage);
                ViewBag.Message = ReturnMessage;
                return RedirectToAction("AddAppointment", "Appointment");
            }
            else 
            {
                ShowMessage(MessageBox.Error, OperationType.Error, ReturnMessage);
            }

            return View(AddBookingVM);
        }

我使用了一个带有提交类型的输入,它正在调用save();关于onclick事件。

<input type="submit" onclick="save();" class="btn btn-default pull-right" value="Book Now"/>

以下是完整的视图代码:

@model ZahidCarWash.ViewModels.AddBookingsViewModel

@{
    ViewBag.Title = "Add Appointment";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<!--  page banner -->
<div id="page-banner" class="page-banner-main" style="background-image: url('Content/images/bg/page-banner.jpg')">
    <div class="container">
        <div class="page-banner-block">
            <div class="section">
                <h3 class="section-heading">Appointments</h3>
            </div>
            <ol class="breadcrumb">
                <li><a href="index-2.html">Home</a></li>
                <li><a href="#">Page</a></li>
                <li class="active"><a>Appointments</a></li>
            </ol>
        </div>
    </div>
</div>
<!--  end page banner  -->
@*@using (Html.BeginForm("AddAppointment", "Appointment", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {*@
<!--  appointments -->
<div id="appointments" class="appointment-main-block appointment-two-main-block">
    <div class="container">
        <div class="row">
            <div class="section text-center">
                <h3 class="section-heading text-center">Get an Appointment</h3>
                @*<p class="sub-heading text-center">Etiam imperdiet imperdiet orci nunc nec neque phasellus leo dolor tempus non auctor.</p>*@
            </div>
            <div class="col-md-4 hidden-sm">
                <div class="appointment-img">
                    <img src="~/Content/images/appointment.jpg" class="img-responsive" alt="Appointment">
                </div>
            </div>
            <div class="col-md-8 col-sm-12">
                <div class="appointment-block">
                    <form id="appointment-form" class="appointment-form" method="post" action="https://mediacity.co.in/autoplus/car-wash/version1/appointment.php">
                        <h5 class="form-heading-title"><span class="form-heading-no">1.</span>Vehicle Information</h5>
                        <div class="row">

                            <div class="col-sm-4">
                                <div class="dropdown">

                                    @Html.DropDownListFor(Model => Model.fk_VehicleMakeID, new SelectList(ZahidCarWash.DAL.VehicleMakesRepository.getVehicleMakes(), "VehicleMakeID", "MakeTitle"),
          new { @class = "form-control" })

                                </div>
                            </div>
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.VehicleModel, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter Vehicle Model" } } )
                            </div>
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.VehicleRegNo, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter Vehicle Reg No." } })
                            </div>
                        </div>
                        <h5 class="form-heading-title"><span class="form-heading-no">2.</span>Available Timings</h5>
                        <div class="row">
                            @*<div class="col-sm-6">
                                    <input type="text" class="form-control date-pick" id="appointment-date" name="appointment-date" placeholder="Appointment Date" required>
                                </div>*@
                            <div class="col-sm-6">
                                <div class="dropdown">
                                    @Html.DropDownListFor(Model => Model.fk_TimeSlotID, new SelectList(ZahidCarWash.DAL.TimeSlotsRepository.getTimeSlots(), "TimeSlotID", "FromTo"), new { @class = "form-control" })
                                    @Html.ValidationMessageFor(Model => Model.fk_TimeSlotID, "", new { @class = "ErrorMessages" })

                                </div>
                            </div>
                        </div>
                        <h5 class="form-heading-title"><span class="form-heading-no">3.</span>Contact Details</h5>
                        <div class="row">
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.CustomerName, new { htmlAttributes = new { @class = "form-control", placeholder = "Customer Name" } })
                                @Html.ValidationMessageFor(Model => Model.CustomerName, "", new { @class = "ErrorMessages" })
                            </div>
                            <div class="col-sm-4">
                                @Html.EditorFor(Model => Model.ContactNo, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter Contact Number." } })
                                @Html.ValidationMessageFor(Model => Model.ContactNo, "", new { @class = "ErrorMessages" })
                            </div>
                            @*<div class="col-sm-12">
                                    <textarea id="message" name="message" rows="6" placeholder="Message"></textarea>
                                </div>*@
                        </div>
                        <input type="submit" onclick="save();" class="btn btn-default pull-right" value="Book Now"/>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

您有url: '@Url.Action("Appointment", "AddAppointment")',,但您的控制器操作名称为:public ActionResult AddAppointment(AddBookingsViewModel AddBookingVM)

(更新)

但你的行动中也有RedirectToAction $ .ajax - $.ajax应该有回应。

尝试通过将脚本更改为此来发送HttpPost交易:

function save() {
    var BookingDetails =
    {
        VehicleModel: document.getElementById('VehicleModel').value,
        VehicleRegNo: document.getElementById('VehicleRegNo').value,
        AppointmentTime: '1',
        CustomerName: document.getElementById('CustomerName').value,
        ContactNo: document.getElementById('ContactNo').value
    }

    var form = document.createElement("form");
    var url = '@Url.Action("Appointment", "AddAppointment")';
    form.setAttribute("method", "POST");
    form.setAttribute("action", url);
    for (var key in BookingDetails) {
        if (data.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", data[key]);
            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
    form.remove();
}

这是一个直的HttpPost,在脚本中无法返回。它创建一个表单,附加数据(通过创建隐藏的输入)发送到操作,将表单添加到DOM,提交然后删除它。

答案 1 :(得分:1)

如上所述,将按钮类型更改为“按钮”。删除onclick属性并添加“id”。我们将使用此ID来捕获按钮单击。

<input type="button" id="btnSubmit" class="btn btn-default pull-right" value="Book Now"/>

将表单声明更改为以下内容。看起来你已将它注释掉了!

@using (Html.BeginForm("", "", FormMethod.Post, new { id = "frmMyForm" }))
{
   //HTML here
}

捕获Jquery中的单击,序列化表单并将表单发布到控制器。

$(document).on("click", "#btnSubmit", function () {

    var data = $("#frmMyForm").serialize();

    $.ajax({
        async: true,
        type: "POST",
        data: data,
        url: "/Appointment/AddAppointment/",
        success: function () {
            //Do stuff here if needed
        },
        complete: function () {
            //Stuff here if needed
        }
    });
});

希望能帮到你的路上,