Javascript 为什么返回原始JSON对象而不是我的部分视图?

Javascript 为什么返回原始JSON对象而不是我的部分视图?,javascript,json,ajax,asp.net-mvc,Javascript,Json,Ajax,Asp.net Mvc,当我提交表单时,页面被重定向到一个包含原始json对象的新窗口,而不是显示我为测试设置的警报。我猜这与从控制器返回Json结果有关,但我对ajax或Json的经验不足,不知道为什么会发生这种情况 局部视图(命名的页脚按钮) 控制器 [HttpPost] public IActionResult Daily(Daily dailyReport) { var dr = new ReportDaily(); var rc = new ReportDailyCriteria();

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

局部视图(命名的页脚按钮)

控制器

[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对象

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

<partial name="../Shared/_FooterButtons" />
}
{"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"}

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

第一:将returnfalse添加到onclick事件

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

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

我已经尝试了你的两个建议,但是表单仍然以正常方式发布,并且仍然会显示一个带有json的页面。检查控制台,可能有一个错误避免javascript按预期运行。在发布之前或之后,控制台中没有错误。我也尝试过将按钮切换到带有按钮类型的输入,但也不起作用。是否需要删除
FormMethod.Post
从视图中创建表单的位置?否,您只需确保表单在创建时已分配ID:
ID=“reportForm”
在浏览器上检查HTML源代码,并在此处发布您的表单标记,因此,我可以编辑答案并使其正常工作。这里是直接来自开发人员工具的HTML:
{"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"}
<button type="button" onclick="submit(); return false" id="submit-form" class="btn btn-primary" value="Print" style="display: inline-block">Print</button>
<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>
$(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);
                    }
                }
            });
        });
});