使用 AJAX 调用服务器端方法
本文关键字:方法 服务器端 调用 AJAX 使用 | 更新日期: 2023-09-27 18:37:05
我正在研究 asp.net,我有以下 c# 方法将网格视图数据导出到 excel 工作表,此方法通过 ImageButton 单击事件调用:
public void GridToExcel()
{
if (berthOccupancyDataGridView.Rows.Count > 0)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=BerthOccupancy.xls");
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
berthOccupancyDataGridView.RenderControl(htw);
if (reportType == "Year To Date")
{
foreach(GridView gv in gridViewList)
{
gv.RenderControl(htw);
}
}
else
{
recapGridView.RenderControl(htw);
}
Response.Write(sw.ToString());
Response.End();
}
}
我有存储动态创建的网格视图的列表。问题是"图像"按钮触发回发并将此列表设置为空。我尝试了很多方法来阻止它执行PostBack,例如使用OnClienClick="return false;",但它不起作用。我尝试使用脚本管理器和WebMethods,但它需要将方法设置为静态并将方法设置为静态显示以下错误:
错误 2 非静态字段、方法或属性"System.Web.UI.Page.Response.get"
需要对象引用 错误 5 非静态字段、方法或属性"BerthOccypancyForm.berthOccupancyDataGridView"需要对象引用
有没有办法在不使用WebMethods和PageMethods的情况下使用AJAX调用此方法?
感谢您的帮助..
所以我在更新面板中有一个gridview
控件,它基本上为用户提供了一个数据列表,如下所示:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView runat="server" ID="transactionGrid" CssClass="table table-bordered table-condensed table-striped"
AllowPaging="true" PageSize="8" AutoGenerateColumns="false" ShowHeaderWhenEmpty="true"
OnRowCommand="transactionGrid_RowCommand"
OnRowDataBound="transactionGrid_RowDataBound"
OnPageIndexChanging="transactionGrid_PageIndexChanging">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<a runat="server" href="~/PayrollManagement/Transaction/TransactionEntry.aspx" class="btn btn-success btn-outline btn-sm"><i class="fa fa-plus fa-fw"></i> Add</a>
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton runat="server" ID="cmdPrint" CssClass="btn btn-success btn-outline ttip btn-sm" ToolTip="Print Batch" data-toggle="tooltip"
CommandName="printBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-print fa-fw"></i></span>
</asp:LinkButton>
<asp:LinkButton runat="server" ID="cmdExportCSV" CssClass="btn btn-success btn-outline ttip btn-sm" ToolTip="Export Batch" data-toggle="tooltip"
CommandName="exportBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-envelope fa-fw"></i></span>
</asp:LinkButton>
<asp:LinkButton runat="server" ID="cmbEditBatch" CssClass="btn btn-primary btn-outline ttip btn-sm" ToolTip="Edit Batch" data-toggle="tooltip"
CommandName="editBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-pencil fa-fw"></i></span>
</asp:LinkButton>
<asp:LinkButton runat="server" ID="cmdPost" CssClass="btn btn-danger btn-outline ttip btn-sm" ToolTip="Post Batch" data-toggle="tooltip"
CommandName="postBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-archive fa-fw"></i></span>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Batch ID" DataField="HEADERID" />
<asp:BoundField HeaderText="Payroll Name" DataField="PAYROLLNAME" />
<asp:BoundField HeaderText="Date Created" DataField="DATECREATED" dataformatstring="{0:MM/dd/yyyy}" htmlencode="false" />
<asp:BoundField HeaderText="Created By" DataField="CREATEDBY" />
<asp:BoundField HeaderText="Batch Date" DataField="BATCHDATE" dataformatstring="{0:MM/dd/yyyy}" htmlencode="false" />
<asp:BoundField HeaderText="Farm Name" DataField="FARMNAME" />
<asp:BoundField HeaderText="Batch Status" DataField="STATUSDESC" />
<asp:BoundField HeaderText="Batch Desc" DataField="BATCHDESC" />
</Columns>
<PagerStyle CssClass="pagination-ys" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cmdSearch" EventName="click" />
<asp:AsyncPostBackTrigger ControlID="cmdPostBatch" EventName="click" />
</Triggers>
</asp:UpdatePanel>
<div hidden="hidden">
<iframe src="../CSVExport/ExportToCsv.aspx" runat="server" id="csvFrame"></iframe>
</div>
如您所见,在网格视图中,有一个分配给每一行的exportBatch
链接按钮。因此,当用户单击exportBatch
按钮时,我会运行我的代码来编译csv,在您的情况下,它将导出为excel。
所以这是rowcommand method
背后的代码:
protected void transactionGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index;
GridViewRow row;
int batchID;
processPayBatch dal = new processPayBatch();
switch (e.CommandName)
{
case "exportBatch":
index = Convert.ToInt32(e.CommandArgument);
row = transactionGrid.Rows[index];
batchID = Convert.ToInt32(row.Cells[1].Text);
Session["csvbatch"] = batchID;
csvFrame.Attributes["src"] = "/CSVExport/ExportToCsv.aspx";
//Download the CSV file.
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "window.frames[0].document.forms[0].submit();", true);
break;
}
}
因此,当单击行按钮时,我会在iframe中提交表单。这是 ExportToCsv 页面的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
processPayBatch dal = new processPayBatch();
int batchID = (int)Session["csvbatch"];
Session["csvbatch"] = null;
dal.ExportToCSV(batchID);
string csv = dal.csvFile;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Output.Write(csv);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
查询数据库并检索必要的信息并将其编译为 csv 文件。
我选择使用 iframe 的原因是因为如果我必须在 gridview 代码隐藏中执行它,则 response.write 不会运行(因为更新面板)。
谢谢你们的建议。我能够以这种方式解决它。
我添加了一个具有静态列表和静态字符串的静态类。我在 WebForm 中称这个类为类。这样在回发期间保留网格视图的数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
/// <summary>
/// Summary description for Global
/// </summary>
public static class Global
{
public static List<GridView> GridViewList = new List<GridView>();
public static string ReportType = "";
}
以下 C# 函数使用静态类中的数据导出到 excel。
public void GridToExcel()
{
if (berthOccupancyDataGridView.Rows.Count > 0)
{
Response.Clear();
//HttpContext.Current.Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=BerthOccupancy.xls");
//HttpContext.Current.Response.Charset = "";
Response.ContentType = "text/csv";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
berthOccupancyDataGridView.RenderControl(htw);
if (Global.ReportType == "Year To Date")
{
foreach (GridView gv in Global.GridViewList)
{
gv.RenderControl(htw);
}
}
else if(Global.ReportType == "Monthly")
{
recapGridView.RenderControl(htw);
}
Response.Write(sw.ToString());
Response.End();
}
}
代码在回发期间保留列表和变量的数据,从而解决了这个问题:
(这个答案的问题在于会话数据默认在 20 分钟后超时,并且会话不用于存储网格视图等大数据)
这个用于保留 GridViewList 数据:
public List<GridView> Code
{
get
{
if (HttpContext.Current.Session["Code"] == null)
{
HttpContext.Current.Session["Code"] = new List<GridView>();
}
return HttpContext.Current.Session["Code"] as List<GridView>;
}
set
{
HttpContext.Current.Session["Code"] = value;
}
}
这个用于保留字符串数据:
public string RT
{
get
{
if (HttpContext.Current.Session["RT"] == null)
{
HttpContext.Current.Session["RT"] = "" ;
}
return HttpContext.Current.Session["RT"] as string;
}
set
{
HttpContext.Current.Session["RT"] = value;
}
}