【发布时间】:2013-11-21 12:37:56
【问题描述】:
鉴于页面/控件应在不同情况下(查询字符串参数、控件回发、从数据库检索的用户设置)显示不同视图(如选项卡)的场景,我通常会放置一个控件,如 MultiView 或 Placeholder 和像这样切换活动视图索引或 Visible 属性:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TestWebApplication.WebForm2" %>
<%@ Register Src="SomeControl.ascx" TagName="SomeControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server" ID="phControl" Visible="false">
<uc1:SomeControl ID="SomeControl1" runat="server" />
</asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="phNotControl" Visible="false">
Some other content
</asp:PlaceHolder>
</div>
</form>
</body>
</html>
我会根据如下逻辑在代码中切换视图:
using System;
namespace TestWebApplication
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
phControl.Visible = false;
phNotControl.Visible = true;
}
}
}
这是控件:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SomeControl.ascx.cs" Inherits="TestWebApplication.SomeControl" EnableViewState="false" %>
I am the control
以及控件背后的代码:
using System;
namespace TestWebApplication
{
public partial class SomeControl : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("I am the control's Init and I am executing heavy operations <br />");
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("I am the control's Load <br />");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("I am the control's PreRender and I am only called if the control is Visible <br />");
}
}
}
但是,如果所讨论的控件在其初始化和加载事件中有一些相对繁重的工作要做(调用数据库)怎么办?即使控件不可见,它们也会被执行,并且会减慢页面速度。我看到的一种可能的解决方案是移动子控件的 PreRender 方法中的所有工作,因为它不会针对不可见的控件执行。但是,如果控件从某个动态填充的控件(想想下拉列表)接受用户输入,这将不起作用,因为使用选项填充下拉列表的逻辑将不会被执行。
我想出了以下解决方案:
将繁重的工作移到 PreRender 方法中并将其包装在 if(!IsPostBack) 中。然后让 ViewState 保存下拉列表的可能值,ASP.NET 将恢复它。缺点是它使用 ViewState 并增加了页面的大小。
使用 LoadControl 动态创建控件,并将其从后面的代码添加到占位符中。这将触发追赶事件,并且填充下拉列表的代码可以放在它所属的 Init 方法中。缺点是布局是在后面的代码中定义的。查看标记无法看到页面上有哪些控件,查看其背后的代码并不清楚控件将出现在哪里。它还使样式和其他“设计”操作更加困难。
保持原样。缺点是会有额外的数据库查询,如果有很多视图,这些会加起来。
我的实际问题是,如何在不将内容放入 ViewState、不进行多次查询且不将布局拖到后面的代码中的情况下解决这个问题。
【问题讨论】: