2009-12-17 27 views
2

我一直在寻找不同的方法来实现masterpages。正确使用MasterPages

  1. 使用母版仅用于布局,包括共同控制每一页
  2. 包括在母版控制上,使用一个母版抽象基类,并重写它在母版类属性。这导致主页事件不再连接。我可能可以解决这个问题,但是对于单个文本框值来说,还有很长的路要走。
  3. 利用好“醇Page.Master.FindControl()

我读过的FindControl应避免(使用魔法‘LABEL1’字符串,据说使用了过多的资源)和masterpages仅用于布局。如果主页仅用于布局,是否需要复制并粘贴100个页面的常用控件?

处理显示和访问常见网站控件(如搜索)的最佳做法是什么?考虑到其他的选择,使用findcontrol来获得一个masterpage控件似乎并不坏。

回答

0

同意母版页只用于布局,是一种明智的方法,不会将公共控件遗留给用户控件,并以这种方式将它们包含在母版页中。

1

MasterPages就像普通的Page对象一样。这意味着您可以通过公共属性公开内部控件来允许子页面访问,而不必求助于Master.FindControl()。要做到这一点,你只需要在页面中设置MasterType属性(我认为它可以工作,即使没有设置此,但与此你得到intellisense支持,并避免必须做演员)。

这里有一个基本的例子(抱歉,这是在VB中 - 这是复制和从旧项目粘贴):

母版页(的.master):

<%@ Master Language="VB" CodeFile="default.master.vb" Inherits="DefaultMaster" %> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form runat="server"> 
    <ASP:TextBox ID="Search" RunAt="Server"/> 
    <ASP:ContentPlaceHolder ID="Content" RunAt="Server"/> 
    </form> 
</body> 
</html> 

主代码隐藏(.master.vb):

Partial Class DefaultMaster : Inherits MasterPage 
    Public ReadOnly Property SearchBox() As TextBox 
     Get 
      Return Search 
     End Get 
    End Property 
End Class 

访问(的.aspx)页:

<%@ Page Language="VB" MasterPageFile="default.master" CodeFile="page.aspx.vb" Inherits="ExamplePage" %> 
<%@ MasterType TypeName="DefaultMaster" %> 

<ASP:Content ContentPlaceHolderID="Content" RunAt="Server"> 
    <p>This is some content on the page.</p> 
</ASP:Content> 

访问页面的代码隐藏(.aspx.vb):

Partial Class ExamplePage : Inherits Page 
    Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs) Handles MyBase.Load 
     Master.SearchBox.Text = "This page now has access to the master's search box." 
    End Sub 
End Class