我知道这样的问题已经在 SO 上被问过了,我也经历了其中的大部分,但没有人让我满意,所以我发布了我的问题。附件是我的代码。实际上,我正在从数据包中的代码构建一个 jquery 库。看代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayHotProducts();
}
}
private void DisplayHotProducts()
{
var dt = ProductData.GetAllHotProducsts();
if (dt != null && dt.Rows.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" <div id='spotlight_products' class='widget_box center_box'>");
sb.AppendLine("<div class='wintitle'>");
sb.AppendLine(" <div class='inner_wintitle'>");
sb.AppendLine(" Hot Products</div></div>");
sb.AppendLine("<div class='winbody'>");
sb.AppendLine("<div class='mall_focus' id='mall_focus'>");
sb.AppendLine("<a id='bp_carousel_prev'>prev</a>");
sb.AppendLine("<a id='bp_carousel_next'>next</a>");
sb.AppendLine("<div id='bp_carousel'>");
sb.AppendLine(" <div class='carousel_list'>");
for (int i = 0; i < dt.Rows.Count; i=i+5)
{
sb.AppendLine(" <div class='product_list'>");
sb.AppendLine("<div class='bestproduct_wrapper'> <div class='bestproduct'>");
sb.AppendLine(" <div class='icon_best'></div>");
sb.AppendLine("<ul>");
sb.AppendLine(" <li class='best_Img'><span></span><a href='#' target='_blank'> ");
sb.AppendLine(string.Format(" <img src='{0}' width='200' height='200' /></a></li>", dt.Rows[i]["ImagePath"]));
sb.AppendLine("</ul>");
sb.AppendLine(" <p class='product_name'>");
sb.AppendLine(string.Format("<a href='Products/{0}' target='_blank'>{1}</a></p>", dt.Rows[i]["Id"], dt.Rows[i]["Name"]));
sb.AppendLine("</div></div>");
for (int j = i+1; j <= 4; j++)
{
sb.AppendLine("<div class='product_item'>");
sb.AppendLine("<ul><li class='product_Img'>");
sb.AppendLine(string.Format("<a href='Products/{0}'><img src='{1}' width='70' height='70'/></a>", dt.Rows[j]["Id"], dt.Rows[j]["ImagePath"]));
sb.AppendLine("</li></ul>");
sb.AppendLine(string.Format("<p class='product_name'><a href='Products/{0}'>{1}</a></p>", dt.Rows[j]["Id"], dt.Rows[j]["Name"]));
sb.AppendLine("</div>");
}
}
sb.AppendLine(@" </div></div></div></div></div>");
ltlHotProducts.Text = sb.ToString();
}
}
}
我后面的代码只有上面的代码,页面加载触发了两次。
这也是一个用户控件的代码隐藏,放置在一个页面上,我有 3 个类似的控件执行类似的功能,即从代码隐藏构建 jquery 幻灯片。但是上面两个用户控件的 img 标签存在一些问题,因为其中一些缺少图像。放置用户控件的页面也有母版页。现在请给我建议解决方案。
所以层次结构是这样的:
Master Page (master) -> Content Page (aspx) -> Has->3 UserControls (ascx)
请您参考如下方法:
我通常看到 PageLoad 触发两次的两个原因 - 首先,如果您有一个没有 src 属性的 img 标签,IE 和 Chrome 都会再次请求页面,这会导致事件再次触发.其次,如果事件被连接不止一次,它就会触发不止一次;通常,当后面的代码包含事件连接代码(例如,this.PageLoad += ... PageLoad)和页面指令 AutoEventWireup=True 时,我经常看到这种情况发生包含在 aspx 文件中。
