【问题标题】:Proper use of MasterPages正确使用 MasterPages
【发布时间】:2009-12-17 15:30:15
【问题描述】:

我一直在研究实现母版页的不同方法。

  1. 仅将母版页用于布局,包括每个页面上的常用控件
  2. 在母版页上包含控件,使用母版页抽象基类并覆盖母版页类中的属性。这导致母版页事件不再连接。我可能可以解决这个问题,但仅针对单个文本框值还有很长的路要走。
  3. 使用好的'ol Page.Master.FindControl()

我读过应该避免使用 findcontrol(使用魔术“label1”字符串,据说使用了太多资源),并且母版页仅用于布局。如果母版页仅用于布局,我是否可以在 100 个页面中复制和粘贴常用控件?

处理显示和访问常用网站控件(如搜索)的最佳做法是什么?考虑到替代方案,使用 findcontrol 获取母版页控件似乎并没有那么糟糕。

【问题讨论】:

    标签: asp.net master-pages


    【解决方案1】:

    MasterPages 是类,就像普通的 Page 对象一样。这意味着您可以通过公共属性公开内部控制,以允许子页面访问,而无需求助于 Master.FindControl()。为此,您只需要在页面中设置 MasterType 属性(我认为即使不设置它也可以工作,但这样您可以获得智能感知支持并避免进行强制转换)。

    这是一个基本示例(对不起,它是在 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
    

    【讨论】:

      【解决方案2】:

      同意母版页仅用于布局,这是一种明智的做法,即不将通用控件外包给用户控件并以这种方式将它们包含在母版页中。

      【讨论】:

        猜你喜欢
        • 2010-10-18
        • 1970-01-01
        • 2014-07-19
        • 1970-01-01
        • 2012-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多