2013-09-25 2 views
0

내 컨트롤러에서 GetFile 메서드로 파일을 생성하고이를 내보기 에 대한 링크로 반환하고 싶습니다. 사용자는 링크를 클릭하여 파일을 다운로드 할 수 있어야합니다. 어떻게 내 Jquery 함수 (데이터) 섹션에서 이것을 쓸 수 있습니다.Mvc; 보기에 다운로드 가능한 파일을 반환하십시오.

  @model PopulateDropDownList.Models.Populate 
      @using PopulateDropDownList.Models 

      @{ 
       ViewBag.Title = "Index"; 
      } 

      <h2>Index</h2> 

      <script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script> 


      @using (Html.BeginForm("Index", "Home", FormMethod.Post, new {rnctype = "multipart/form-data" })) 
      { 

       <p> 
        @Html.DropDownList("mylist", Helper.GetDescription(),"--select here--") 
        <input id="Button1" type="button" value="button" /> 

       </p> 

       } 


       <script language="javascript" type="text/javascript"> 
        $(document).ready(function() { 
         $("#Button1").click(function() { 
          var SelCat = $("#mylist").val(); 
          if (SelCat != 0) { 
           var url = '@Url.Action("GetFile", "Home")'; 
           $.post(url, { categoryId: SelCat }, 
          function (data) { 

          }); 
          } 
          else { 
           alert("You need to select an city"); 
          } 
         }); 
        }); 
      </script> 




      public FileStreamResult GetFile() 
        { 
         string name = "me.txt"; 
         FileInfo info = new FileInfo(name); 
         if (!info.Exists) 
         { 
          using (StreamWriter writer = info.CreateText()) 
          { 
           writer.WriteLine("Hello, I am a new text file"); 

          } 
         } 
         return File(info.OpenRead(), "text/plain"); 
        } 
+0

당신이 아약스를 사용하여 파일을 다운로드 할 수 없습니다 – Shyju

답변

0

당신은 ActionResult 대신 FileStreamResult에 MVC 작업을 전환 할 수 있습니다. 가 그럼 그냥 일반 링크와 함께 가리, 더 JQuery와 게시물이 필요하지 않습니다 :

<a href="/controller/GetFile"target="_blank"> 
관련 문제