【问题标题】:Why this ajax post request does not work in mvc app为什么这个 ajax 发布请求在 mvc 应用程序中不起作用
【发布时间】:2020-04-27 20:17:12
【问题描述】:

我有带有 ajax 请求的 js 文件

这是正文的一部分

$.ajax({
       url: '/Points/Addpoint', // также '@Url.Action("Addpoint", "PointsController")'
       type: "POST",
       dataType: "json",
       data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx: ev._x, secondy: ev._y }),
       success: function () {
                               alert();
                           }
});  

我也有这个方法的mvc控制器,应该在ajax中调用

[HttpPost]
        public void Addpoint(JSON po)
        {
            var pointslist = this.Getpoints();
            var obj = po;
            pointslist.Add(new Point());

        }

但不知何故,这不起作用。 idk 为什么?它给了我 500 错误和消息

没有为此对象定义无参数构造函数。

我应该怎么做才能解决这个问题并发送这个 json obj?

【问题讨论】:

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


    【解决方案1】:

    将 JSON 更改为类并更改您的帖子

            public class YourClass 
            {
                public string firstx { get; set; }
                public string firsty { get; set; }
                public string secondx { get; set; }
                public string secondy { get; set; }
            }
            [HttpPost]
            public void Addpoint([FromBody] YourClass po)
            {
                var pointslist = this.Getpoints();
                var obj = po;
                pointslist.Add(new Point());
            }
        $.ajax({
               url: '/Points/Addpoint',
               type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
               data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx:ev._x,secondy: ev._y }),
               success: function () {
    
                                   }
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-20
      • 2019-10-26
      • 2020-05-31
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 2018-06-05
      • 2020-10-15
      相关资源
      最近更新 更多