1

I'm having an issue posting a csv file to my action method in the backend. I have an action method called UploadPropertyCSV in Controller PropertyController, which is to process the file and add it to the database, but for some reason when I click submit the file never hits the action method, and just refreshes the page and does nothing. My front-end code looks like the following:

<form id="Form2" method ="post" name="Form2" enctype="multipart/form-data">
    <input type="file" name="file" id="file" multiple />
    <input type="submit" value="Upload" />
</form>

<script>
    $(function () {
        $("#Form2").submit(function (event) {
            var formData = new FormData($("#Form2").get(0));
            $.ajax({
                url: "Property/UploadPropertyCSV",
                type: 'POST',
                dataType: 'json',
                data: formData,
                processData: false,
                contentType: false,
                success: function (result) {
                    alert(result.Message)
                }
            })
        });
    });
</script>

My action method returns JSON messages to be displayed in an alert as per the following method:

 public ActionResult UploadPropertyCSV(HttpPostedFileBase file)
        {
            List<PropertyModel> properties = new List<PropertyModel>();
            TestD dbContext = new TestDB();
            foreach (string requestFiles in Request.Files)
            {
                if (file != null && file.ContentLength > 0 && file.FileName.EndsWith(".csv")) 
                {
                    using(StreamReader str = new StreamReader(file.InputStream))
                    {
                        using(CsvHelper.CsvReader theReader = new CsvHelper.CsvReader(str))
                        {
                            int rowCount = 0;
                            while (theReader.Read())
                            {
                                try { 
                                rowCount++;
                                //theReader.Configuration.HasHeaderRecord = true;
                                //if (theReader.IsRecordEmpty())
                                //{
                                //    RIMUtil.LogError("Empty Row: " + rowCount);
                                //}
                                    RIMUtil.PropertyUploadCSVRowHelper row = new RIMUtil.PropertyUploadCSVRowHelper()
                                    {
                                        UnitNumber = theReader.GetField(0),
                                        StreetNumber = theReader.GetField(1),
                                        StreetName = theReader.GetField(2),
                                        City = theReader.GetField(3),
                                        PostalCode = theReader.GetField(4),
                                        Country = theReader.GetField(5),
                                        NumberOfBedrooms = theReader.GetField(6),
                                        NumberOfBathrooms = theReader.GetField(7),
                                        NumberOfCarSpaces = theReader.GetField(8),
                                        KeyNumber = theReader.GetField(9),
                                        ExternalPropertyID = theReader.GetField(10),// Renamed to extPropertyID
                                        IsVacant = theReader.GetField(11),
                                        PropertyManagerId = theReader.GetField(12),
                                        BuildingName = theReader.GetField(13)
                                    };


                                // Missing field checks
                                List<string> missingFields = new List<string>();

                                if (missingFields.Count > 0)
                                {
                                    RIMUtil.LogError("Row: " + rowCount + "Has a missing mandatory field");
                                    return Json(new { Success = false, Message = "Error: Missing mandatory field!" });
                                }

                                else
                                {
                                    // Invalid field checks
                                        if (invalidFields.Count > 0)
                                        {
                                            return Json(new { Success = false, Message = "Error: An invalid entry exists!" });
                                        }

                                        else
                                        {
                                            Property property = new Property();
                                            //object creation stuff here

                                            dbContext.Properties.Add(property);
                                            dbContext.SaveChanges();
                                        }
                                    }
                                }catch(Exception e)
                                {
                                    return Json(new { Success = true, Message = "CSV is formatted incorrectly" });
                                }
                            }

                            return Json(new { Success = true, Message = "Success!" });
                        }
                    }
                }
                return Json(new { Success = false, Message = "Empty file or wrong file format!" });
            }
            return Json(new { Success = false, Message = "Error Occured!" });
        }

Is there a better way I can write this functionality? The message alert that JSON returns is also unresponsive.

If anyone has any suggestions on a better way to write my front end code or a solution it would be greatly appreciated!

Thanks in advance

5
  • Not related, but your not cancelling the default submit - your making a normal submit and an ajax call (the last line in $("#Form2").submit(function (event) { .... } should be return false; And the method should be IEnumerable<HttpPostedFileBase> file and then you can just loop through the parameter rather than using Request.Files Commented Jul 10, 2016 at 10:26
  • What error messages are you getting in the browser console? Commented Jul 10, 2016 at 10:29
  • Thanks for the tip @StephenMuecke I'm getting error 404 - The resource could not be found Commented Jul 10, 2016 at 11:29
  • Your url is not correct. Always use the Url.Action() method to generate the correct url - url: '@Url.Action("UploadPropertyCSV", "Property")' (which will result in /Property/UploadPropertyCSV Commented Jul 10, 2016 at 11:32
  • This fixed it Thank you so much! Commented Jul 10, 2016 at 12:10

1 Answer 1

1

You need to use preventDefault to ensure the ajax call is made instead of submitting the form.

Sign up to request clarification or add additional context in comments.

1 Comment

This fixed the unresponsive JSON alert message. Thank you bwyn

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.