模型
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();
}
});
}
答案 0 :(得分:1)
您无法使用AJAX下载文件 您需要使用常规页面请求。