简体   繁体   English

MVC-表单上传异常处理

[英]MVC - form upload exception handling

I have a controller method which returns response to download. 我有一个控制器方法可以返回下载响应。 It is working fine but when there is an exception occurs a blank page returned on the current page, where download is requested. 它工作正常,但是当出现异常时,在当前页面返回空白页面,请求下载。

Also I am sending some form data to request the download. 另外,我正在发送一些表格数据以请求下载。

Instead I need to show the error message as popup. 相反,我需要将错误消息显示为弹出窗口。 How could I do that? 我该怎么办?

MVC Controller Method to download pdf. MVC Controller Method下载pdf。 Its return pdf to download but sometimes when exception occurs it return a blank page. 它返回pdf以供下载,但有时在发生异常时返回空白页。

  [HttpPost]
  public void Downloadpdf()
  {
      try
      {
        // Generate pdf
            Response.Clear();
            Response.AddHeader("Content-Type", "application/pdf");
            Response.AddHeader("Content-Disposition", "attachment;filename=Newpdf.pdf");
            byte[] pdf = ms.ToArray();
            Response.OutputStream.Write(pdf, 0, pdf.Length);
            Response.End();

       }
       catch (Exception ex)
       {
           Response.End();
       }
   }  

How should I show popup for the exception. 我应该如何显示该异常的弹出窗口。 And avoid blank page. 并避免空白页。 Also it is a Single Page Application. 也是单页应用程序。

1) Remove void and use ActionResult 1)删除空白并使用ActionResult

2) Use "return View("YourViewName");" 2)使用“返回View(“ YourViewName”);” after catch statement 在catch语句之后

3) In catch, add a line: ViewBag.Exception = ex; 3)在catch中,添加一行:ViewBag.Exception = ex;

4) On the view where you return, type 4)在您返回的视图上,键入

@if(ViewBag.Exception == null)
{
}
else
{
@ViewBag.Exception
}

5) You want to show on popup, use alert on the same view using javascript. 5)您想在弹出窗口上显示,使用javascript在同一视图上使用警报。

Hope the points satisfy your problem. 希望这些点能解决您的问题。

in you main page,put a iframe 0 width 0 height 在您的首页中,放置一个iframe 0宽度0高度
when click download button ,set the iframe src to you download action 单击下载按钮时,将iframe src设置为您要下载的操作
if everything is ok,return File(...) 如果一切正常,请返回File(...)
if has some error ,return View(...) 如果有错误,请返回View(...)
and the view show in iframe,you can use some js to control the main page in iframe page to popup 并在iframe中显示视图,您可以使用一些js来控制iframe页面中的主页弹出

main page 主页

function pop(){....}  

iframe page iframe页面

$(function(){ window.parent.pop(); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM