I am working with the Telerik Upload. To parse a excel file to then dump data into the database. That part seems to work the problem that is happening that I am trying to check the Success or Error on the return and it just going to the blank screen. With the content message or the json message. It is not attaching back to the event on the Telerik Upload. I am looking for a fix see code below.
[HttpPost]
public ActionResult UploadContactTaskAsync(IEnumerable<IFormFile> files, int campaign, int mec)
{
try
{
var phoneOperatiors = new List<PhoneOperators>();
Stream FileStream = null;
IExcelDataReader eReader;
if (files == null || !files.Any())
{
//ContentResult contentResult = new ContentResult
//{
// Content = "No files selected for upload.",
// ContentType = "text/plain",
// StatusCode = 400 // Bad Request
//};
return BadRequest(new { message = "No file selected or file is empty." });
//return Json(new { success = false, message = "No files selected for upload." });
}
else
{
var file = files.FirstOrDefault();
if (file != null && file.Length > 0)
{
FileStream = file.OpenReadStream();
if(file.FileName.EndsWith(".xls"))
{
eReader = ExcelReaderFactory.CreateBinaryReader(FileStream);
}
else if(file.FileName.EndsWith(".xlsx"))
{
eReader = ExcelReaderFactory.CreateOpenXmlReader(FileStream);
}
else if (file.FileName.EndsWith(".csv"))
{
eReader = ExcelReaderFactory.CreateCsvReader(FileStream);
}
else
{
return Json(new { success = false, message = "Unsupported file format. Please upload an Excel or CSV file." });
}
var excelRecords = eReader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration()
{
UseHeaderRow = true // To use first row as column names
}
});
eReader.Close();
if(excelRecords.Tables.Count > 0)
{
var dataTable = excelRecords.Tables[0];
foreach (DataRow row in dataTable.Rows)
{
var pilotId = row["PilotId"].ToString();
bool existsInMec = _context.Pilot.Any(f => f.PilotId == pilotId && f.PortalId == mec);
bool existsInCampaign = _context.PhoneOperators.Any(f => f.PilotId == pilotId && f.ContactListId == campaign && f.PortalId == mec);
if (existsInMec && !existsInCampaign)
{
PhoneOperators phoneOperator = new PhoneOperators
{
PilotId = pilotId,
Active = true,
ContactListId = campaign,
PortalId = mec,
CreateDate = DateTime.Now,
CreateUser = _httpContextAccessor.HttpContext?.User?.Identity?.Name
};
phoneOperatiors.Add(phoneOperator);
}
}
_context.PhoneOperators.AddRange(phoneOperatiors);
_context.SaveChanges();
}
}
}
_toastNotification.AddSuccessToastMessage("Files uploaded successfully.");
return Json(new { success = true, message = "Files uploaded successfully." });
}
catch (Exception ex )
{
_logger.LogError(ex, "Failed to upload files");
_toastNotification.AddErrorToastMessage("Failed: " + ex.Message, new ToastrOptions { ExtendedTimeOut = 0 });
return Json(new { success = false, message = ex.Message });
}
function onSuccess(e) {
e.preventDefault();
if (e.response && e.response.success) {
alert("File uploaded successfully.");
} else {
alert("File upload failed: " + (e.response ? e.response.message : "Unknown error"));
}
var uploadWindow = $("#uploadContactTaskWindow").data("kendoWindow");
uploadWindow.close();
}
function onError(e) {
e.preventDefault();
var status = e.XMLHttpRequest.status;
var statusText = e.XMLHttpRequest.statusText;
var serverErrorMessage = e.XMLHttpRequest.responseText;
if (serverErrorMessage)
{
}
var errorContainer = $("#errorContainer");
e.errors.forEach(function (error) {
errorContainer.append("<div class='alert alert-danger'>" + error + "</div>");
});
}@using (Html.BeginForm("UploadContactTask", "PhoneOperators", FormMethod.Post, new { enctype = "multipart/form-data", id = "uploadContactTaskForm" }))
{
<input id="Mec" type="hidden" name="Mec" value="@Model.PortalId"/>
<div id="errorContainer">
</div>
<div class="container form-group">
<div class="row">
@( Html.Kendo().DropDownList()
.Name("Campaign")
.OptionLabel("- Campaign -")
.DataTextField("ListName")
.DataValueField("ContactListId")
.AutoBind(true)
.HtmlAttributes(new { style = "width: 400px;" })
.DataSource(ds =>
{
ds.Read(read =>
{
read.Action("GetMecContactList", "App").Data("getMecFilterLocal");
})
.ServerFiltering(true);
})
)
</div>
<div class ="row" style="margin-top:5em">
<div class="col-md-10">
@(
Html.Kendo().Upload()
.Name("files")
.Validation(validation => validation
// Pass an array of allowed extensions (include the dot)
.AllowedExtensions(new string[] { ".csv", ".xlsx" })
)
.Async(s => s
.Save("UploadContactTask", "PhoneOperators").AutoUpload(false))
.Events(e => e.Success("onSuccess").Error("onError"))
)
</div>
</div>
<div class="row" style="margin-top: 3em" >
<button type="submit" class="btn btn-primary" id="uploadButton">Upload</button>
</div>
</div>
}
<style>
.k-clear-selected,
.k-upload-selected {
display: none;
}
</style>