无法将CSV文件上传到Controller Action

时间:2016-07-10 10:20:26

标签: javascript jquery json asp.net-mvc csv

我在向后端的action方法发布csv文件时遇到问题。我在Controller PropertyController中有一个名为UploadPropertyCSV的动作方法,它处理文件并将其添加到数据库中,但出于某种原因,当我单击提交时,文件永远不会访问动作方法,只刷新页面并且什么都不做。我的前端代码如下所示:

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

我的操作方法按照以下方法返回要在警报中显示的JSON消息:

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

有没有更好的方法可以编写此功能? JSON返回的消息警报也没有响应。

如果有人对更好的方法来编写我的前端代码或解决方案有任何建议,我们将不胜感激!

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要使用preventDefault来确保调用ajax而不是提交表单。