猿问

下载 CSV 文件并显示 Sweet Alert 错误消息

我有一个带有文本区域的视图(用户在其中输入所有订单)和一个提交按钮,


一旦按下“提交”按钮,操作方法将处理所有订单并将它们保存在数据库中。


如果所有订单均已成功处理,我将返回到带有指示器 (ViewBag) 的视图,该指示器将从 JavaScript 中弹出一个甜蜜的警报。


如果一个或多个订单失败,我将下载一个 csv 文件来显示失败的订单。


此外,我想返回到视图,以便我可以显示一条甜蜜的警报错误消息。


我知道如何下载该文件,并且知道如何返回错误消息和甜蜜警报。


我只是不知道如何同时做这两件事:)


我知道我不能同时发送 2 个请求,我有什么选择?


控制器中的提交按钮操作:


public IActionResult AddOrdersExtension(OrderVM orderVM)

{

  if (ModelState.IsValid)

  {

  //

   foreach(var order in ordersList)

   {

     if(isStoreAuthenticated(orderVM)) 

       _unitOfWork.Order.Add(orderVM.Orders);

       _unitOfWork.Save();

     else

     {

       failedLines = failedLines + "," + orderVM.Orders.CustName;

     }

   }

   if (failedLines.Length > 0)

   {

    ViewBag.Failed = true;

    StringBuilder sb = new StringBuilder();

    //

    // populate string builder with failed line

    //

    // downlaod csv file

   return File(Encoding.ASCII.GetBytes(sb.ToString()), "text/csv", "Error_log.csv");

  }

  else // all orders processed successfully

{

  ViewBag.Failed = false;

  return View(orderVM);

}

}

视图中的 Java 脚本:


@section Scripts{

  if (ViewBag.failed)

     {

     <script>

       swal("Error Occured!", "Failed to process All Orders", "error")

                                .then((value) => {})

            </script>

    }

    else

    {

       <script>

         swal("Success!", "Orders were Processed Successfully!", "success")

                    .then((value) => { window.location.href = '/UserRole/Order'; })

       </script>

    }

}


SMILET
浏览 81回答 1
1回答

德玛西亚99

正如你所说,你不能同时返回两个响应,我将通过一个文本区域来解决它,其中包含显示失败订单的 CSV 数据,并可以选择将文本下载到文件中您可以使用此 Javascript 函数从 TextArea 下载文件function generateTextFile(textareaElement, filenameWithoutExtension) {&nbsp; &nbsp; var textToWrite = textareaElement.val();&nbsp; &nbsp; var textFileAsBlob = new Blob([textToWrite], {type:'text/csv'});&nbsp; &nbsp; var fileNameToSaveAs = filenameWithoutExtension + ".csv";&nbsp; &nbsp; var downloadLink = document.createElement("a");&nbsp; &nbsp; downloadLink.download = fileNameToSaveAs;&nbsp; &nbsp; downloadLink.innerHTML = "Download File";&nbsp; &nbsp; if (window.webkitURL != null) {&nbsp; &nbsp; &nbsp; &nbsp; // Chrome allows the link to be clicked&nbsp; &nbsp; &nbsp; &nbsp; // without actually adding it to the DOM.&nbsp; &nbsp; &nbsp; &nbsp; downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; // Firefox requires the link to be added to the DOM&nbsp; &nbsp; &nbsp; &nbsp; // before it can be clicked.&nbsp; &nbsp; &nbsp; &nbsp; downloadLink.href = window.URL.createObjectURL(textFileAsBlob);&nbsp; &nbsp; &nbsp; &nbsp; downloadLink.onclick = destroyClickedElement;&nbsp; &nbsp; &nbsp; &nbsp; downloadLink.style.display = "none";&nbsp; &nbsp; &nbsp; &nbsp; document.body.appendChild(downloadLink);&nbsp; &nbsp; }&nbsp; &nbsp; downloadLink.click();}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答