最近开始用Firefox来调试WEB程序,发现在Firefox下会在页面完全加载成功后,再重新执行一遍Page_Load之前(含Page_Load)的所有代码,而在IE下运行正常。
test.aspx 代码:
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312"
AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="b_test" %>
<asp:Literal runat="server" ID="ltlCss" />
test.aspx.cs:
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class b_test : System.Web.UI.Page
... {
protected void Page_Load(object sender, EventArgs e)
...{
if (Page.IsPostBack)
...{
return;
}
string Sql = "UPDATE WB_T_U_User SET iVisit=iVisit+1 WHERE B_ID=1";
Response.Write(Sql);
ExecuteSql(ref Sql);
ltlCss.Text = "<link type="text/css" rel="stylesheet" id="Link1" href="theme/default/c.css" />";
}
protected void ConnOpen()
...{
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Sql"].ToString();
try ...{ conn.Open(); }
catch ...{ Response.Write("数据库链接失败!<br />" + conn.ConnectionString); Response.End(); }
cmd.Connection = conn;
ada.SelectCommand = cmd;
}
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter ada = new System.Data.SqlClient.SqlDataAdapter();
public int ExecuteSql(ref string Sql)
...{
cmd.CommandText = Sql;
int iCount = 0;
try
...{
iCount = cmd.ExecuteNonQuery();
}
catch (System.Exception ex)
...{
ConnError(ex.ToString());
}
finally
...{
Sql = null;//conn.Close(); conn.Dispose(); cmd.Dispose(); conn = null; cmd = null;
}
return iCount;
}
}
执行结果在Firefox(版本2.0.0.9) 下会在加载完后,再执行Page_Load(),也就是数据更新了两次;
而在IE下运行正常,只执行一次。这个算是Firefox的BUG呢,还是ASP.NET的问题?
本想用SESSION来解决这个问题了,幸好在Truly的博客里找到了问题的原因所在。
直接引用他的原话:
在.net 2.0 环境下,要特别主要html和js的写法。
如果页面上出现src=""类似等效属性或样式,会导致对某些页面发生请求,导致Page_Load执行两次或更多, 使页面性能直线下降。
例如<img src="#">,改语句将导致本页面Pag_Load多次执行。
因为#表示对本页的某个锚点请求,当页面下载到此处时,会Request本页面。
而如果<img src="">, 那么会对本级虚拟路径的默认页进行请求,
例如http://www.abc.com/blog/test.aspx 页面上有此标记,那么页面加载到此标记时会对http://www.abc.com/blog/发生请求,如果有默认页,那么默认页会被加载。因此要去掉src="#" 和 src=""。
同时还有一些样式,例如<td background="#ffffff">,也将对本页进行请求,因为浏览器首先将background的属性值作为图片进行请求,所以,浏览器认为td的background为“xxx.aspx?#fffff”这个图片,应该改为<td bgcolor="#ffffff"> 或 <td style="background-color:#ffffff">。
一检查前台页面代码,还真有一个img的src="",将src属性去掉就一切正常了。
真是奇怪的.NET,奇怪的问题。