【问题标题】:Why doesn't the ajax post data to the controller?为什么 ajax 不向控制器发布数据?
【发布时间】:2018-04-04 12:24:33
【问题描述】:

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

@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);
        }

我使用了一个类型为 submit 的输入,它正在调用 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>

【问题讨论】:

  • 您是否在浏览器的控制台中检查了呼叫是否触发了服务器?并分享控制台信息。
  • 您似乎有一个提交按钮,但您指定了一个 onclick 事件。它是哪一个?提交表单内容的提交按钮或带有事件的按钮,大概您想序列化表单的内容并执行 ajax 发布?
  • @wheels 我发的那个
  • @Stacky - 好的。第一次测试....将按钮类型更改为“按钮”。向您的函数添加一个简单的警报并验证该函数是否被命中。

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


【解决方案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
        }
    });
});

希望对你有所帮助,

【讨论】:

    【解决方案2】:

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

    (更新)

    但您的 $.ajax 操作中也有 RedirectToAction - $.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,提交然后删除它。

    【讨论】:

    • @Stacky - 更新了答案 - 如果这不起作用,请尝试简化代码以先获得结果,然后从那里构建。
    猜你喜欢
    • 2018-12-22
    • 2021-02-14
    • 2017-03-06
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2020-03-25
    • 2014-01-22
    相关资源
    最近更新 更多