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
$("#Form2").submit(function (event) { .... }should bereturn false;And the method should beIEnumerable<HttpPostedFileBase> fileand then you can just loop through the parameter rather than usingRequest.FilesUrl.Action()method to generate the correct url -url: '@Url.Action("UploadPropertyCSV", "Property")'(which will result in/Property/UploadPropertyCSV