0
  1. 当我使用提交按钮并将 Excel 导出代码放入控制器 POST 操作时,下面的代码运行良好。
  2. 现在我不想回发并移动下面的代码,但现在报告没有下载,虽然控制器操作“ExcelExport”按预期调用,但报告没有下载?请建议这里有什么问题?

模型

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Decimal Price { get; set; }

    public Product(int id, string name, string description, decimal price)
    {
        Id = id;
        Name = name;
        Description = description;
        Price = price;
    }

    static readonly List<Product> AllProducts = new List<Product>
    {
        new Product(1, "Games Console", "Fun for all the family", 199.99m),
            new Product(2, "MP3 player", "Listen to your favourite tunes on the move", 99.99m),
            new Product(3, "Smart Phone", "Apps, apps, apps", 399.99m),
            new Product(4, "Digital Photo frame", "All your photos in one beautiful frame", 49.99m),
            new Product(5, "E-book reader", "Take your favourite books on the move with you", 149.99m),
            new Product(6, "DVD Box Set", "All of season one plus exclusive extras", 39.99m)
    };

    public static List<Product> GetAllProducts()
    {
        return AllProducts;
    }

控制器

public ActionResult Index()
    {
        return View();
    }


    public ActionResult ExcelExport()
    {
        var products = Product.GetAllProducts();

        var grid = new GridView();
        grid.DataSource = from p in products
                          select new
                          {
                              ProductName = p.Name,
                              SomeProductId = p.Id
                          };
        grid.DataBind();

        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

        Response.ContentType = "application/excel";

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);

        Response.Write(sw.ToString());

        Response.End();

        return Content("tr");
    }

看法

@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{


<div id="rptExport" style="display: none">
</div>

<input type="button" id="ExportExcelButton" value="Export To Excel" onclick="ExportExcel()" />
}

<script type="text/javascript">
//global cache false
$.ajaxSetup({ cache: false });

function ExportExcel() {
    //block the UI until the request is rendered
    $.blockUI({ message: '<h3><b><img src="@Url.Content("~/content/images/loading.gif")" />Please wait while Processing</b></h3>' });

    $('#rptExport').load('@Url.Action("ExcelExport", "Home")', function (data) {
        var urlFile = "";
        if (data != '') {
            debugger;
            //unblock the UI     
            $.unblockUI();
        }
    });
}

4

1 回答 1

1

您不能使用 AJAX 下载文件。
您需要使用常规页面请求。

于 2012-08-28T15:01:21.610 回答