对按钮点击事件使用一种方法
本文关键字:一种 方法 按钮 事件 | 更新日期: 2023-09-27 18:00:27
所以我有一个我目前正在开发的网站。有几个页面将包括GridView
,用户可以在其中下载文件。目前,我正在为每个页面编写下载方法。有更好的方法来实现这一点吗?即在每次点击事件时调用此方法
我正在使用以下代码
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment;filename='"" + Path.GetFileName(filePath));
Response.ContentType = "application/pdf";
Response.WriteFile(filePath);
Response.End();
}
我可能会使用一个通用处理程序。如果这是一个小项目,我只是想缩短代码,您可以考虑一个简单的扩展方法。
方法1:通用处理程序
将下载内容写入通用处理程序。下面的代码可以是你网站上的"DownloadPdf.ashx"。
public class DownloadPdf : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string filePath = Uri.UnescapeDataString(context.Request.QueryString["file"]);
string contentType = Uri.UnescapeDataString(context.Request.QueryString["type"]);
context.Response.ContentType = contentType;
context.Response.AppendHeader("Content-Disposition", "attachment;filename='"" + Path.GetFileName(filePath));
context.Response.ContentType = "application/pdf";
context.Response.WriteFile(filePath);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
然后,在您的事件处理程序中:
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
string url = string.Format("~/DownloadPdf.ashx?contentType={0}&file={1}", Uri.EscapeDataString(ContentType), Uri.EscapeDataString(filePath));
Response.Redirect(url);
}
方法2:扩展
如果你只是想在一个简单的项目上缩短代码,你可以写一个扩展方法。
public static class Extensions
{
public static void WritePdfDownload(this HttpResponse response, string filePath, string contentType)
{
response.ContentType = contentType;
response.AppendHeader("Content-Disposition", "attachment;filename='"" + Path.GetFileName(filePath));
response.ContentType = "application/pdf";
response.WriteFile(filePath);
response.End();
}
}
然后,您的事件处理程序非常简单:
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.WritePdfDownload(filePath, ContentType);
}
创建一个可以从所有应该能够下载文件的页面访问的类,然后在"onclick()"中简单地调用该类。
如果页面上有公共逻辑,也许应该考虑使用下载方法创建基类,然后为其他页面继承这个基类。
您将有一个下载方法的实现,这将使其更易于维护。
您还可以将下载文件的方法提取到单独的类中,并从页面中调用if,但现在看来,您需要弄清楚如何将其他依赖项传递到那里,比如Response
对象。
在静态下载类中编写DownloadFile方法
将方法签名中的"object Response"替换为Response对象的类型。
namespace DownloadMethods
{
internal static class Downloads
{
public static void DownloadFile(object sender, object Response)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment;filename='"" + Path.GetFileName(filePath));
Response.ContentType = "application/pdf";
Response.WriteFile(filePath);
Response.End();
}
}
}
你可以称之为:
protected void DownloadFile(object sender, EventArgs e)
{
DownloadMethods.Downloads.DownloadFile(sender, Response);
}