2012-12-27 2 views
1

안녕하세요 저는 Gridview를 파일로 변환하는 내보내기 클래스를 만들었습니다.MVC에서 Ajax를 사용할 때 엑셀로 내보내기가 작동하지 않습니다.

DownloadFileActionResult 클래스 :

public class DownloadFileActionResult : ActionResult 
    { 


     public GridView ExcelGridView { get; set; } 
     public string fileName { get; set; } 


     public DownloadFileActionResult(GridView gv, string pFileName) 
     { 

      ExcelGridView = gv; 

      fileName = pFileName; 

     } 



     public override void ExecuteResult(ControllerContext context) 
     { 

      HttpContext curContext = HttpContext.Current; 
      curContext.Response.ClearContent(); 
      curContext.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls"); 
      curContext.Response.ContentType = "application/vnd.ms-excel"; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter htw = new HtmlTextWriter(sw); 
      ExcelGridView.RenderControl(htw); 
      curContext.Response.Write(sw.ToString()); 
      curContext.Response.End(); 

     } 

    } 

JQuery와 - 아약스 :

function Export(){ 


    var search = {};           
    search.Name = "MaterialShape"; 
    search.Description = ""; 
    search.Address =""; 

    var url_ = generateURL("/Home/Download");     //Call Save Controller and pass details entities 

    $.ajax({ 
     type: "POST", 
     url: url_, 
     data: search,           //details will act as the Entities Model 
     traditional: true, 
     success: function(data) { 


     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
       alert("error: " + XMLHttpRequest.responseText); 
     }, 
     dataType: 'json' 
    }); 

}; 

가 검색 Parmeter 속성 :

public class SearchParams 
    { 
     public string Name{ get; set; } 
     public string Description {get;set;} 
     public string Address{get;set;} 
     ... 
    } 

그리고 내가 구현

코드 아래 참조

 //Export to excel 
    public ActionResult Download(SearchParam param) 
    { 

     List<Lookup> lookupList = data.GetLookup(param); 
     var grid = new System.Web.UI.WebControls.GridView(); 

     grid.DataSource = lookupList; 
     grid.DataBind(); 

     return new DownloadFileActionResult(grid, "test"); 

    } 

그것은 (검색 PARAM 값없이) 작동하고 내가 컨트롤러 URL을 입력 할 때 수동으로

http://localhost:54928/Home/Download 

또는 html.action 링크

<%= Html.ActionLink("Home", "/Download", "Home")%> 

를 사용하지만 내 컨트롤러 t 아약스 전화를 사용할 때 작동하지 않습니다.

<img src="<%=Url.Content("~/Images/export.png")%>" id="Img1" onclick="Export();" alt="Export" /> 

정말 사용해야합니다.

나는 여기에 뭔가를 놓치고 있습니다. 모든 아이디어? 그것은 다운로드 $.ajax를 사용하는 것이 이해가되지 않습니다

답변

2

감사에서

덕분에 파일을 엑셀 - 아약스 호출이 정말 JS 코드에서 텍스트 기반 데이터 (. HTML을 XML, JSON)을 취득하기위한 것입니다 있도록 그것으로 작업 할 수 있습니다. 브라우저는 Excel과 같은 바이너리 콘텐츠를 처리하는 방법 (예 : 파일 저장 여부를 묻는 메시지)을 알고 있습니다. 이 경우

은 모든 당신이 간단한 POST입니다 필요/여기

+0

내 문제 (단순 document.location = "/home/download?q=keyword"; 한) 엑셀 파일 다운로드를 시작하기 위해 요청을 GET하는 것은 내가/JQuery와 승 일반 목록을 사용하여 조회/보고서를 가지고있다 매개 변수 및 아약스 메서드를 사용하는 사이의 암시 관계를 무엇인지 모르겠다. 필자는 실제로 모델/Entity를 매개 변수로 사용할 필 요가 많은 데이터베이스가있는 datatables를 참조하십시오. 감사합니다. – BizApps

+0

@BizApps? js 객체를 URL로 인코딩 된 데이터로 직렬화하려면'$ .param'을보십시오. AFAIK, ASP.NET MVC 측의 기본 모델 바인더는 쿼리 문자열 값을 모델/엔티티 매개 변수로 변환 할 수 있어야합니다. – VinayC

+0

감사합니다 @VinayC, 난 그냥 내 모든 필터의 값을 연결하고 컨트롤러 감사 내 코드에 그것을 분할하려고합니다. – BizApps

관련 문제