在 page_load 里加上如下代码:
string beforeSubmitJS = "\nvar exportRequested = false; \n";
beforeSubmitJS += "var beforeFormSubmitFunction = theForm.onsubmit;\n";
beforeSubmitJS += "theForm.onsubmit = function(){ \n";
beforeSubmitJS += "var returnVal = beforeFormSubmitFunction(); \n";
beforeSubmitJS += "if(exportRequested && returnVal) {_spFormOnSubmitCalled=false; exportRequested=false;} \n";
beforeSubmitJS += "return returnVal; \n";
beforeSubmitJS += "}; \n";
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alterFormSubmitEvent", beforeSubmitJS, true);
注册javascript程序,然后再按钮提交时发送一个参数:
this._btnSubmit.Attributes["onclick"] = "javascript:exportRequested=true;";
这样可以解决这个问题。
原理:页面按钮提交时会调用一个内置的方法并修改一个内置变量_spFormOnSubmitCalled,我们通过按钮来调用方法重置
这个参数的值,达到系统检索页面时,一直默认为未提交状态。
================注意点1=====================================
但是,如果是ascx 控件上 点击导出按钮,而不是aspx页面上点击按钮,那么 上面的方法会报错,
._btnSubmit为导出Excel文件的Button;
RegisterClientScriptBlock将代码注册到源文件后面,RegisterStartupScript的话,由于theForm.onsubmit 没有声明,会报错
================注意点2=====================================
生成的excel文件如果选择"打开",是很正常的;
选择“保存”,页面上的所有脚本失效,前题还必须是target为_self
错误信息为“未知错误“
个人分析认为这个是生成的页面虽然弹出打开,但设置的setHeader已经默认为excel文件格式,这个引响到了IE调用JS的方式(猜测),现在解决的方法为将target设为_blank,不过结果是会多一个白色的页面
================注意点2=====================================
protected void Page_Load(object sender, EventArgs e)
{
btnExcel = (Button)FindControl("btnExcel");
#region [moss里用Response生成Excel或word以后页面按钮失效问题,解决办法]
string beforeSubmitJS = "/nvar exportRequested = false; /n";
beforeSubmitJS += "var beforeFormSubmitFunction = theForm.onsubmit;/n";
beforeSubmitJS += "theForm.onsubmit = function(){ /n";
beforeSubmitJS += "var returnVal = beforeFormSubmitFunction(); /n";
beforeSubmitJS += "if(exportRequested && returnVal) {_spFormOnSubmitCalled=false; exportRequested=false;} /n";
beforeSubmitJS += "return returnVal; /n";
beforeSubmitJS += "}; /n";
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alterFormSubmitEvent", beforeSubmitJS, true);
this.btnExcel.Attributes["onclick"] = "javascript:exportRequested=true;";
#endregion
if (!Page.IsPostBack)
{
Page.DataBind();
}
}