代码之家  ›  专栏  ›  技术社区  ›  Niels Bosma

ASP.NET:自定义由页驱动的母版页的最佳方法

  •  1
  • Niels Bosma  · 技术社区  · 15 年前

    我有相当简单的网站结构,有一个手帕和一大堆网页。不过,mastepage非常高级,我需要从页面上控制masterpage的某些方面。

    我希望能够在ASPX文件中输入这些指令,以避免混乱文件背后的代码。

    我的想法是创建不同的“指令”用户控件,如seodirective:

    using System;
    
    public partial class includes_SeoDirective : System.Web.UI.UserControl
    {
    
        public string Title { get; set; }
    
        public string MetaDescription { get; set; }
    
        public string MetaKeywords { get; set; } 
    
    }
    

    我在那些需要覆盖默认mastepage设置的页面中包含这个指令。

    <offerta:SeoDirective runat="server" Title="About Us" MetaDescription="Helloworld"/>
    

    在我的主页上,我查看是否有任何指示:

    includes_SeoDirective seo = (includes_SeoDirective) ContentPlaceHolder1.Controls.Children().FirstOrDefault(e => e is includes_SeoDirective);
    

    (children()是一个扩展,因此我可以在ControlCollection上使用Linq)

    现在我的问题是:我不高兴这个解决方案可能有点臃肿?

    我正在寻找替代的解决方案,我可以在ASPX文件中创建这些标签。

    我看过扩展页面的技巧,但这需要我们修改vs配置以便项目编译,所以我放弃了那个解决方案。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Codesleuth    15 年前

    据我所知,没有一种标准的方法可以做到这一点。我过去做过同样的事情,和你做过的差不多,只是我用了 interface 在我需要主控页查找的页面上,它定义了一个方法,它可以调用该方法来对主控页执行特定的逻辑。

    您可能可以使用相同的范例:

    ispecialpage.cs:电子邮箱:

    public interface ISpecialPage
    {
        string Title { get; set; }
    
        string MetaDescription { get; set; }
    
        string MetaKeywords { get; set; } 
    }
    

    MyPage.aspx:

    public partial class MyPage : System.Web.UI.Page, ISpecialPage
    {
        public string Title { get; set; }
    
        public string MetaDescription { get; set; }
    
        public string MetaKeywords { get; set; }
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
            this.Title = "Some title";
            this.MetaDescription  = "Some description";
            this.MetaKeywords = "Some keywords";
        }
    }
    

    母版页。母版:

    public partial class MasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Context.Handler is ISpecialPage)
            {
                ISpecialPage specialPage = (ISpecialPage)this.Context.Handler;
                // Logic to read the properties from the ISpecialPage and apply them to the MasterPage here
            }
        }
    }
    

    这样,您就可以处理母版页代码隐藏文件中的所有母版页逻辑,并且只需在需要提供某些信息的页上使用接口。

    希望这对你有帮助!