skip to Main Content

I am trying to upload an excel file to database in MVC5, which happens successfully, it then should show the data that has been uploaded. I am doing both these actions in a single action method

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);
}

I am then trying to get this data using jquery ajax as below –

$("#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);
                    }
                });

But upon running the code the page asks to download the data as a json file, instead of going into the success block. Initially, I thought it’s because the data is large. Even this doesn’t work –

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

My 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>

2

Answers


  1. Chosen as BEST ANSWER

    Looks like the below code was the issue. Will need to investigate more as to why -

    @using (Html.BeginForm("UploadExcel", "UploadData", FormMethod.Post, new { enctype = "multipart/form-data" }))
    

    I simply replaced it with a regular html form and then added below code to get post the file object in the javascript -

    var $file = document.getElementById('inputGroupFile02'),
                    $formData = new FormData();
    
                if ($file.files.length > 0) {
                    for (var i = 0; i < $file.files.length; i++) {
                        $formData.append('file-' + i, $file.files[i]);
                    }
                }
    

    and added the following inside the ajax call -

                    data: $formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
    

    At the controller, got the file object using

                    if (Request.Files.Count > 0)
                    {
                        foreach (string file in Request.Files)
                        {
                            var _file = Request.Files[file];
                        }
                    }
    

    I think there was probably some conflict with the FormMethod.Post and ajax post. I could be wrong. Feel free to correct this and add to what could be the issue.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search