【问题标题】:Mvc; Return a downloadable file to a viewMVC;将可下载文件返回到视图
【发布时间】:2013-09-25 19:04:04
【问题描述】:

我想在我的控制器的 GetFile 方法中生成一个文件并将它作为一个链接返回 我的观点。用户应该能够单击链接并下载文件。我怎样才能在我的 Jquery 函数(数据)部分写这个。

            @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");
                    }

【问题讨论】:

  • 无法使用 ajax 下载文件

标签: jquery asp.net-mvc-3


【解决方案1】:

您可以将 MVC 操作切换为 ActionResult 而不是 FileStreamResult。 然后只需用常规链接指向它,不需要 jquery 帖子:

<a href="/controller/GetFile"target="_blank">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多