首页 > 解决方案 > Jquery Ajax 要求下载 JSON 文件而不是进入成功块

问题描述

我正在尝试将一个 excel 文件上传到 MVC5 中的数据库,这成功发生了,它应该显示已上传的数据。我在单个操作方法中执行这两个操作

public ActionResult UploadExcel(HttpPostedFileBase file)
{
          //logic to upload and get uploaded data into a DataTable "dataLoadedTable"
          ..
          ..
          string JSONresult;
          JSONresult = JsonConvert.SerializeObject(dataLoadedTable);
          return Json(JSONresult, JsonRequestBehavior.AllowGet);
}

然后我尝试使用 jquery ajax 获取这些数据,如下所示 -

$("#formId").on("submit", function () {
            $.ajax
                ({
                    url: 'UploadExcel',
                    type:'POST',
                    datatype: 'application/json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (response) {
                        alert(response);
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                        alert(status);
                        alert(error);
                    }
                });

但是在运行代码时,页面要求将数据下载为 json 文件,而不是进入成功块。最初,我认为这是因为数据很大。即使这样也行不通-

success: function (response) {
  alert("hi");
},

我的 HTML -

@using System.Data
@model DataTable
@{
    ViewBag.Title = "Upload Excel";
    Layout = "~/Views/Shared/_CommonLayout.cshtml";
}


<body>
    @using (Html.BeginForm("UploadExcel", "UploadData", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <form id="myDataForm">
            <div>
                <h4>Upload Data</h4>
                <div class="card shadow">
                    <div class="p-5">

                        <label>Upload File:</label>
                        <div class="input-group mb-3">
                            <div class="custom-file">
                                <input type="file" name="file" autofocus="autofocus" class="custom-file-input" id="inputGroupFile02" />
                                <label class="custom-file-label" for="inputGroupFile02">Choose file</label>
                            </div>
                            <div class="input-group-append">
                                <button class="btn btn-primary" id="btnUploadData">Upload</button>
                            </div>
                        </div>
                        <script>
                            $('#inputGroupFile02').on('change', function () {
                                //get the file name
                                //var fileName = $(this).val();
                                var fileName = $(this).val().split('\\').pop();;
                                //replace the "Choose a file" label
                                $(this).next('.custom-file-label').html(fileName);

                            })
                        </script>

                        <!--Display Error Message-->
                        <div style="color:red;">@ViewBag.Message</div>


                        @if (!string.IsNullOrWhiteSpace(ViewData["Upload Success"] as String))
                        {
                            <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
                                @Html.ViewData["Upload Success"]
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                        }


                    </div>
                </div>
            </div>
        </form>
    }
    <table id="dataTable" class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>ABC</th>
                <th>XYZ</th>
                ..
                ..
            </tr>
        </thead>
    </table>
</body>

标签: jqueryjsonajaxasp.net-mvc-5json.net

解决方案


You need to prevent the form being submitted. Call preventDefault() on the event passed to the submit handler:

$("#formId").on("submit", function(e) {
  e.preventDefault();

  // your ajax here...
});

In addition, you don't appear to be sending any data in your AJAX request? I'm going to assume this was accidentally removed when you wrote out the question.

Also, just as an aside, don't use alert() for debugging. It blocks the browser and coerces data types, which is the last thing you need when data consistency. Use console.log() or console.dir() instead.


推荐阅读