2012-07-26 5 views
5

내 응용 프로그램이 MVC 3, .net을 사용하여 구현되었습니다. 버튼 클릭만으로 Excel 파일을 생성하려고합니다. Ajax를 사용하여 컨트롤러 조치를 호출합니다. 내 주요 문제는 다음과 같습니다. 파일 생성 중에 사용자에게 입력 작업을 알리려면 화면에 이미지를 표시하려고합니다. 이미지를 잘 표시 할 수 있지만 작업이 완료된 후에는 이미지를 숨길 수 없습니다. codei 사용하고 있습니다 :컨트롤러 동작 완료 후 Javascript를 사용하여 이미지 숨기기 MVC3

자바 스크립트 코드 :

$("input.DownloadExcelReport").click(function (e) { 
    e.preventDefault(); 
    var parameter = -- code to fetch parameter value; 
    var outputViewUrl = (the url is created here); 
    showLoading(); -- This function displays the image 
    window.location.href = outputViewUrl; 
}); 

컨트롤러 액션 코드 :

public ActionResult DownExcelReportForAssortment(Guid parameter) 
{ 

     try 
     { 

      //the contents for the file generation are fetched here.. 
      // Write contents to excel file 
      if (memoryStream != null) 
      { 
       var documentName = "Report.xls"; 
       byte[] byteArrary = memoryStream.ToArray(); 
       return File(byteArrary, "application/vnd.ms-excel", documentName); 
      } 
     } 
     catch (Exception ex) 
     { 
      LogManager.LogException(ex); 
     } 
} 

나는에 코드를 작성할 수 있습니다 자바 스크립트 메소드 호출로 JSON 결과를 반환하지 않습니다 이미지를 숨 깁니다. 사용자가 저장할 수있는 파일을 반환하고 작업이 완료되었습니다.

파일 생성 작업이 완료되면 어떻게 이미지를 숨길 수 있습니까?

도움을 감사합니다

...

답변

9

당신은 following article을 체크 아웃 할 수 있고 행동으로이 넣어. 그래서 우리는 컨트롤러를 정의하여 시작합니다

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult DownExcelReportForAssortment(Guid parameter, string tokenId) 
    { 
     // Simulate some heavy work to fetch the report 
     Thread.Sleep(5000); 

     // we fake it 
     byte[] byteArray = System.IO.File.ReadAllBytes(@"c:\test.xls"); 

     var cookie = new HttpCookie("fileDownloadToken", tokenId); 
     Response.AppendCookie(cookie); 

     return File(byteArray, "application/vnd.ms-excel", "report.xls"); 
    } 
} 

및 뷰에서 :

@Html.ActionLink(
    "download report", 
    "DownExcelReportForAssortment", 
    "Home", 
    new { parameter = Guid.NewGuid(), tokenId = "__token__" }, 
    new { @class = "download" } 
) 

지금 마지막 단계는

jquery.cookie 플러그인 포함 :

<script type="text/javascript" src="@Url.Content("~/scripts/jquery.cookie.js")"></script> 

과에 스크립트를 작성 앵커의 클릭 이벤트에 가입하고 다운로드 진행 상황을 추적하십시오.

$(function() { 
    var fileDownloadCheckTimer; 

    $('.download').click(function() { 
     var token = new Date().getTime(); 
     $(this).attr('href', function() { 
      return this.href.replace('__token__', token); 
     }); 

     // Show the download spinner 
     $('body').append('<span id="progress">Downloading ...</span>'); 

     // Start polling for the cookie 
     fileDownloadCheckTimer = window.setInterval(function() { 
      var cookieValue = $.cookie('fileDownloadToken'); 
      if (cookieValue == token) { 
       window.clearInterval(fileDownloadCheckTimer); 
       $.cookie('fileDownloadToken', null); 

       // Hide the download spinner 
       $('#progress').remove(); 
      } 
     }, 1000); 
    }); 
}); 
+0

쿠키 문제를 피하기 위해 세션 변수를 사용하여 처리하는 것을 선호합니다. 그래서 당신은 액션에서 장시간 실행되는 코드 뒤에 세션 변수를 설정하고 js에서 비슷한 폴링 스크립트를 사용하여 세션이 존재하는지 확인하기 위해 ajax 요청을 다른 액션으로 보냅니다. 그렇다면 세션을 종료하고 js 콜백에 대한 'true'응답을 반환하고 로더를 끕니다. –

관련 문제