【问题标题】:Ajax success function not receiving data ASP.NET MVCAjax 成功函数未接收数据 ASP.NET MVC
【发布时间】:2019-12-25 14:14:20
【问题描述】:

我可以正确地将数据添加到数据库中,但是 Ajax 成功功能不起作用。我总是得到错误函数:

查看:

<div id="dvform">
    <!-- some data-->
    <input type="submit" value="submit" id="btnsubmit" />
</div>

<script>
        $(document).ready(function () {
            $("#btnsubmit").click(function () {
                addAppointment();
            });
        });
            function addAppointment (){
                $.ajax({
                    type: 'POST',
                    url: '/FuelerAppointments/Create',
                    contentType: 'application/json; charset=utf-8',
                    dataType: "html",
                    data: $("dvform").val(),

                    success: function (data) {
                      swal("Done!", "The appointment was saved successfully!", "success");
                    },
                    error: function (data) {

                         swal("Error deleting!", "Please try again", "error");
                     },
                });
            }

控制器:

[HttpPost]
public ActionResult Create(FuelerAppointment fuelerAppointment)
{
    return Json(fuelerAppointment, JsonRequestBehavior.AllowGet);
}

【问题讨论】:

标签: ajax asp.net-mvc post asp.net-ajax


【解决方案1】:

首先您应该将dataType: "html", 更改为dataType: "json", 并在 $.ajax() 之前创建 FuelerAppointment 对象:

        var fuelerAppointment = {};  
        fuelerAppointment.Name = $("#Name").val(); 

然后是ajax方法中的数据

data: '{fuelerAppointment: ' + JSON.stringify(fuelerAppointment) + '}',

欲了解更多信息,请查看此链接Using AJAX In ASP.NET MVC

【讨论】:

    【解决方案2】:

    dataType: "html" 更改为dataType: "json"


    在数据属性中你应该这样写

    var model = {
         prop1: prop1Value,
         prop2: prop2Value,
         ...
    };
    data: {fuelerAppointment: model}
    

    或者

    
    data: JSON.stringify({
       fuelerAppointment: {
            prop1: prop1Value,
            prop2: prop2Value,
            ...
       }
    })
    

    注意事项:fuelerAppointment 对象应该在 C# 类中表现出 sem 属性

    【讨论】:

      猜你喜欢
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 2013-08-04
      • 1970-01-01
      • 2018-04-08
      • 2013-02-14
      • 2017-01-24
      相关资源
      最近更新 更多