【问题标题】:Why is the raw JSON object getting returned instead of my partial view?为什么返回原始 JSON 对象而不是我的部分视图?
【发布时间】:2020-02-24 18:00:30
【问题描述】:

当我提交表单时,页面会被重定向到带有原始 json 对象的新窗口,而不是显示我为测试设置的警报。我猜这与从控制器返回 Json 结果有关,但我对 ajax 或 json 的经验不足,不知道为什么会发生这种情况。

局部视图(名为 _FooterButtons)

<div class="row col-12">
    <div class="col-12 footerbuttons">
        <button type="button" onclick="submit()" id="submit-form" class="btn btn-primary" value="Print" style="display: inline-block">Print</button>
        <input type="button" class="btn btn-secondary" value="Cancel" />
    </div>
</div>

主视图

@using (Html.BeginForm("Daily", "Reports", FormMethod.Post, new { id = "reportForm", @class = "report-form col-9" }))
{
...

<partial name="../Shared/_FooterButtons" />
}

JavaScript

$(document).ready(function () {
    $("#startdatepicker").datepicker();
    $("#enddatepicker").datepicker();

    // Add the listener only when everything is loaded
    window.onload = function () {
        // Get the form
        let rform = document.getElementById('reportForm');
        console.log(rform);
        // Add the listener
        rform.addEventListener('submit', function (e) {
            // Avoid normal form process, so no page refresh
            // You'll receive and process JSON here, instead of on a blank page
            e.preventDefault();
            // Include here your AJAX submit:
            console.log("Form submitted");
            $.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 {
                        alert("Data Fail");
                        $('#errorsModal').modal('toggle');
                        $('#errorsModal .modal-body label').html(data.message);
                    }
                }
            });
        });
    };
});

控制器

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

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

在新窗口中返回的 Json 对象

{"success":false,"message":"Must select a payment Source, County and/or Municipal.\r\n\r\nMust select at least one payment type.\r\n\r\nMust select at least one user.\r\n\r\n"}

【问题讨论】:

    标签: javascript json ajax asp.net-mvc


    【解决方案1】:

    您需要避免正常的表单流程,您有两种选择:

    首先:在onclick事件中添加return false。

    <button type="button" onclick="submit(); return false" id="submit-form" class="btn btn-primary" value="Print" style="display: inline-block">Print</button>
    

    只有在单击按钮时才会执行第一个选项,但如果在输入时按下 ENTER 键则可能不会执行。

    第二个更好的选择:在表单中添加事件监听器:

    <script>
    // Add the listener only when everything is loaded
    window.onload = function() {
        // Get the form
        let rform = document.getElementById('reportForm');
        // Add the listener
        rform.addEventListener('submit', function(e) {
            // Avoid normal form process, so no page refresh
            // You'll receive and process JSON here, instead of on a blank page
            e.preventDefault();
            // Include here your AJAX submit:
            console.log("Form submitted");
            $.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 {
                        alert("Data Fail");
                        $('#errorsModal').modal('toggle');
                        $('#errorsModal .modal-body label').html(data.message);
                    }
                }
            });
        });
    };
    </script>
    

    编辑:由于您使用的是 jQuery .ready(),所以情况有些不同:

    $(document).ready(function () {
        $("#startdatepicker").datepicker();
        $("#enddatepicker").datepicker();
    
        // Not really sure if window.onload inside .ready() was the problem,
        // but it could be
    
            // Get the form and add the listener
            $("#reportForm").on('submit', function (e) {
                // Avoid normal form process, so no page refresh
                // You'll receive and process JSON here, instead of on a blank page
                e.preventDefault();
    
                console.log("Form submitted");
                $.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 {
                            alert("Data Fail");
                            $('#errorsModal').modal('toggle');
                            $('#errorsModal .modal-body label').html(data.message);
                        }
                    }
                });
            });
    });
    

    【讨论】:

    • 我已经尝试了你的两个建议,但表单仍然以正常方式发布,并且仍然会打开一个带有 json 的页面。
    • 检查控制台,可能有错误导致javascript无法按预期运行。
    • 在发布之前或之后控制台中没有错误。我也尝试将按钮切换为带有某种按钮的输入,但这也不起作用。我是否需要从视图上创建表单的位置删除FormMethod.Post
    • 不,您只需要确保表单具有创建时分配的 ID:id = "reportForm" 检查浏览器上的 HTML 源并在此处发布您的表单标签,以便我可以编辑答案并制作它工作
    • 这里是直接来自开发者工具的 HTML:&lt;form action="/Reports/Reports/Daily" class="report-form col-9" id="reportForm" method="post"&gt;
    【解决方案2】:

    我使用了类似于 Triby 建议的方法,但我没有在表单提交上添加事件侦听器,而是在提交按钮单击上添加了一个事件侦听器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      相关资源
      最近更新 更多