Necesito ejecutar una funcion javascript desde mi controller de .net core.
Tengo un controlador el cual me genera dos archivos unos csv y otro xlsx, el tema es que como he consultado en internet me funciona solamente cuando llamo desde el el controlador index pero desde otro no me funciona , quien pueda ayudarme lo agradezco.
Código que me funciona hasta ahora es el siguiente:
en el html:
<script type="text/javascript">
function ShowGreetings(name) {
alert("Name: " + name);
};
</script>
@if (ViewBag.JavaScriptFunction != null)
{
<script type="text/javascript">
@Html.Raw(ViewBag.JavaScriptFunction)
</script>
}
<div class="container">
<br />
<h1 style="color: #58b5db; font-family:Bahnschrift" class="my-3 mx-2"><i class="fa fa-upload"></i> Upload File</h1>
<br />
<div class="form-group col-12">
@using (Html.BeginForm("Upload", "UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<label for="file" class="col-1" align="right">File:</label>
<input type="file" id="file" name="file" class="form-control-file col-11" onchange="return fileValidation()">
</div>
<br />
<div class="form-group row">
<div id="msgError" style="color:red; font-size:18px; font-family:Bahnschrift;"></div>
<div class="col-12">
<button disabled="disabled" id="btnUpload" type="submit" class="btn btn-primary" onclick="cargarLoader()">Upload File</button>
</div>
<div id="loader" class="loader" style="display:none"></div>
</div>
}
</div>
</div>
en el controller:
public ActionResult Index()
{
ViewBag.JavaScriptFunction = string.Format("ShowGreetings('{0}');", "jesus");
return View();
}
sin embargo cuando intento llamar la misma funcion javascript desde otro controlador que es donde estoy creando los archivos no me funciona, el codigo del siguiente controlador es:
[HttpPost]
public IActionResult Upload()
{
WSS_MP_AddressValidatorPortTypeClient wsUploadFile = new WSS_MP_AddressValidatorPortTypeClient();
ViewBag.JavaScriptFunction = string.Format("ShowGreetings('{0}');", "jesus");
if (Request.Form.Files.Count > 0)
{
var file = Request.Form.Files[0];
if (file != null && file.Length > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fileNameAlone = Path.GetFileNameWithoutExtension(file.FileName);
string extension = Path.GetExtension(file.FileName);
if (extension == ".csv")
{
var csvParserService = new CsvParserService();
var carpetaTemp = @"C:\Tmp";
string fullPath = Path.Combine(carpetaTemp, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
var readFile = csvParserService.ReadCsvFileToEmployeeModel(fullPath);
if (readFile is null)
{
ViewBag.msgError = "The file structure is incorrect please verify";
}
else
{
//Enviar archivo a servicio
List<string> stringArrayService = new List<string>();
foreach (var item in readFile)
{
stringArrayService.Add(item.IDSEQ +","+ item.ID_ENTITY + "," + item.ADDR1 + "," + item.ADDR2 + "," + item.CITY + "," + item.STATE + "," + item.ZIP);
}
var operationAdd = new mplt_MailPrep_AV_FileVal_Operation { IADD = stringArrayService.ToArray() };
using (var scope = new OperationContextScope(wsUploadFile.InnerChannel))
{
// Adding required Azure subscription key header
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
//Linea de seguridad AZURE
requestMessage.Headers["Ocp-Apim-Subscription-Key"] = "20b37b6673404435872ee14a2ec327eb";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
var result = wsUploadFile.mplt_MailPrep_AV_FileVal_OperationAsync(operationAdd).Result;
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream);
var csvWriter = new CsvWriter(streamWriter);
csvWriter.WriteHeader<ArchiveCSVModel>();
csvWriter.NextRecord();
List<string> oADD = result.mplt_MailPrep_AV_FileVal_OperationResponse.OADD.ToList();
csvWriter.Configuration.RegisterClassMap<ArchiveCSVMap>();
List<ArchiveCSVModel> parts = new List<ArchiveCSVModel>();
ArchiveCSVModel temp = new ArchiveCSVModel();
//var archivo = new string[];
foreach (var data in oADD)
{
var records = data.Split(",");
temp.IDSEQ = records[0];
temp.ID_ENTITY = records[1];
temp.ADDR1 = records[2];
temp.ADDR2 = records[3];
temp.CITY = records[4];
temp.STATE = records[5];
temp.ZIP = records[6];
temp.ADDR1_STD = records[7];
temp.ADDR2_STD = records[8];
temp.CITY_STD = records[9];
temp.STATE_STD = records[10];
temp.ZIP_STD = records[11];
temp.MAILABILITY = records[12];
temp.STATUS_DESC = records[13];
temp.STATUS = records[14];
parts.Add(temp);
temp = new ArchiveCSVModel();
}
csvWriter.WriteRecords(parts);
streamWriter.Flush();
memoryStream.Position = 0;
//ViewBag.JavaScriptFunction = string.Format("ocultarLoader();");
//ViewBag.Loader("ocultarLoader();");
return File(memoryStream, "text/csv", fileNameAlone + "_" + DateTime.Now.Year + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + extension);
}
}
}
else
if (extension == ".xlx" || extension == ".xlsx")
{
ExcelPackage package = new ExcelPackage(file.OpenReadStream());
DataTable Dt = ExcelPackageExtensions.ToDataTable(package);
List<string> stringArrayService = new List<string>();
foreach (DataRow dr in Dt.Rows) {
stringArrayService.Add(dr[0] + "," + dr[1] + "," + dr[2] + "," + dr[3] + "," + dr[4] + "," + dr[5] + "," + dr[6]);
}
var operationAdd = new mplt_MailPrep_AV_FileVal_Operation { IADD = stringArrayService.ToArray()};
//var operationAdd = new[]
// {
// new mplt_MailPrep_AV_FileVal_Operation{ADD = Dt.ToString()}
// };
using (var scope = new OperationContextScope(wsUploadFile.InnerChannel))
{
// Adding required Azure subscription key header
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
//Linea de seguridad AZURE
requestMessage.Headers["Ocp-Apim-Subscription-Key"] = "20b37b6673404435872ee14a2ec327eb";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
var result = wsUploadFile.mplt_MailPrep_AV_FileVal_OperationAsync(operationAdd).Result;
byte[] resultFinally;
using (var createExcelPackage = new ExcelPackage())
{
var worksheet = createExcelPackage.Workbook.Worksheets.Add("FinallyAddress");
worksheet.Cells["A1"].Value = "IDSEQ";
worksheet.Cells["B1"].Value = "ID_ENTITY";
worksheet.Cells["C1"].Value = "ADDR1";
worksheet.Cells["D1"].Value = "ADDR2";
worksheet.Cells["E1"].Value = "CITY";
worksheet.Cells["F1"].Value = "STATE";
worksheet.Cells["G1"].Value = "ZIP";
worksheet.Cells["H1"].Value = "ADDR1_STD";
worksheet.Cells["I1"].Value = "ADDR2_STD";
worksheet.Cells["J1"].Value = "CITY_STD";
worksheet.Cells["K1"].Value = "STATE_STD";
worksheet.Cells["L1"].Value = "ZIP_STD";
worksheet.Cells["M1"].Value = "MAILABILITY";
worksheet.Cells["N1"].Value = "STATUS_DESC";
worksheet.Cells["O1"].Value = "STATUS";
int i = 2;
foreach (var test in result.mplt_MailPrep_AV_FileVal_OperationResponse.OADD)
{
int cont = 1;
foreach (string word in test.Split(','))
{
switch (cont)
{
case 1:
worksheet.Cells["A" + i].Value = word;
cont = cont + 1;
break;
case 2:
worksheet.Cells["B" + i].Value = word;
cont = cont + 1;
break;
case 3:
worksheet.Cells["C" + i].Value = word;
cont = cont + 1;
break;
case 4:
worksheet.Cells["D" + i].Value = word;
cont = cont + 1;
break;
case 5:
worksheet.Cells["E" + i].Value = word;
cont = cont + 1;
break;
case 6:
worksheet.Cells["F" + i].Value = word;
cont = cont + 1;
break;
case 7:
worksheet.Cells["G" + i].Value = word;
cont = cont + 1;
break;
case 8:
worksheet.Cells["H" + i].Value = word;
cont = cont + 1;
break;
case 9:
worksheet.Cells["I" + i].Value = word;
cont = cont + 1;
break;
case 10:
worksheet.Cells["J" + i].Value = word;
cont = cont + 1;
break;
case 11:
worksheet.Cells["K" + i].Value = word;
cont = cont + 1;
break;
case 12:
worksheet.Cells["L" + i].Value = word;
cont = cont + 1;
break;
case 13:
worksheet.Cells["M" + i].Value = word;
cont = cont + 1;
break;
case 14:
worksheet.Cells["N" + i].Value = word;
cont = cont + 1;
break;
case 15:
worksheet.Cells["O" + i].Value = word;
cont = cont + 1;
break;
default:
ViewBag("Error in request of service");
break;
}
}
i++;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
resultFinally = createExcelPackage.GetAsByteArray();
return File(resultFinally, "application/vnd.ms-excel", fileNameAlone + "_" + DateTime.Now.Year + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + extension);
}
}
}
}
}
wsUploadFile.CloseAsync();
return View("Index");
}
}
}