【问题标题】:Unable to serialize asp dot net core form using ajax request无法使用 ajax 请求序列化 asp dot net core 表单
【发布时间】:2021-01-04 19:11:22
【问题描述】:

我正在开发一个 asp.net 核心应用程序。我有一个表单,我想使用 ajax 对其进行发布请求。我正在使用的表格非常大。我不想做这样的事情

var email = $("input[name='email']"); 因为真的很大。

控制器没有接收到用户输入的任何值。它只是空的。

我是这样做的:

 $("#submit").click(function () {

        $.ajax({
            type: "post",
            url: "/Employee/Create",
            dataType: 'json',
            contentType: false,
            processData: false,
            data:  $("#form1").serialize(),

            success: function (response) {
                console.log(response.length);
              
               
            }
        });
});

#form1 是表单的 ID。

有没有其他方法可以代替serialize()?或者我必须这样做var email = $("input[name='email']"); 这个。还是我的代码格式不正确?

请帮忙。

【问题讨论】:

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


    【解决方案1】:

    那是因为contentType:false告诉jQuery不要设置任何内容类型头,你需要删除它。然后它会设置默认的内容类型"application/x-www-form-urlencoded; charset=UTF-8"

    $("#submit").click(function () {
    
        $.ajax({
            type: "post",
            url: "/Employee/Create",
            dataType: 'json',
            //contentType: false,    //remove this...
            processData: false,
            data: $("#form1").serialize(),
            success: function (response) {
                alert("success");
                console.log(response.length);
            }
        });
    });
    

    确保您的后端代码如下所示:

    [HttpPost]
    //[ValidateAntiForgeryToken]   //be sure do not have this attribute
    public JsonResult Create(Employee employee)
    {
        //do your stuff...
        return Json(employee);
    }
    

    结果:

    【讨论】:

      【解决方案2】:

      您也可以将表单序列化如下。

      $("#submit").click(function () {
          const dataToSend = new FormData(form.get(0));
                   $.ajax({
                          url: actionUrl,
                          type: 'POST',
                          url: "/Employee/Create",
                          dataType: 'json',
                          data: dataToSend,
                          processData: false,
                          contentType:false,
                          success: function(response) {...}
               });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 2021-08-19
        • 2022-01-24
        相关资源
        最近更新 更多