【问题标题】:Ajax serialized form with values not getting passed correctly to my controller's action值未正确传递给控制器​​操作的 Ajax 序列化表单
【发布时间】:2020-02-25 17:02:53
【问题描述】:

我设置了一个 javascript 警报以确认我的 form.serialize 工作正常,而且确实如此。问题是我的控制器操作没有将表单中的任何数据关联到模型。

带有传递的表单值的 Javascript 警报

此警报中的第一个值是StartDate,其值为02/25/2020,但在下方控制器的屏幕截图中,它没有绑定到dailyReport 对象的StartDate 值。

控制器和传递对象的屏幕截图

Ajax

$(function () {
    $('#submit').on('click', function (evt) {
        alert($('#reportForm').serialize());
        evt.preventDefault();
        //Ajax form post
        $.ajax({
            type: 'POST',
            data: $('#reportForm').serialize(),
            url: '@Url.Action("Daily","Reports")',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.success) {
                    alert("Data Success");
                } else {
                    console.log(data);
                    //Toggle the error modal and display error messages
                    $('#errorsModal').modal('toggle');
                    //Add <br> tags when there is a linebreak in the string.  This will add the line breaks into the HTML.
                    $('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
                }
            }
        });
    });
});

控制器

[HttpPost]
public IActionResult Daily(Daily dailyReport)
{
    var dr = new ReportDaily();
    var rc = new ReportDailyCriteria();
    dr.Preview(rc, IntPtr.Zero, out Notification notification);
    if (notification.HasErrors)
    {
        return Json(new
        {
            success = false,
            message = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)
        });
    }

    return Json(new { success = true });
}

【问题讨论】:

  • 怎么样:数据:JSON.stringify($('#reportForm').serialize())
  • @Adlorem 不幸的是,这没有用。我也试过JSON.stringify({ dailyReport: $("#reportForm").serialize() })。 dailyReport 是我的对象参数的名称。
  • 请显示您的控制器操作
  • @Adlorem 添加了控制器动作
  • 谢谢。改变一下呢: contentType: 'application/json; charset=utf-8' to: dataType: 'html',因为实际上你并没有在 post 方法中传递 json。

标签: javascript jquery ajax asp.net-mvc


【解决方案1】:

从使用'application/json; charset=utf-8' 切换到'application/x-www-form-urlencoded; charset=utf-8' fixed the issue.

【讨论】:

    猜你喜欢
    • 2014-08-22
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多