如何从母版页访问唯一页面的公共页面变量?

时间:2011-01-19 03:01:46

标签: c# asp.net master-pages

我有一个页面 - 整个网站只有一页:

using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CMSPageViewer : System.Web.UI.Page
{
    public int myPageID;

    protected void Page_PreInit(object sender, EventArgs e)
    {
         // Get stuff from the database

         myPageID = 1;

         // Set the Page.MasterPageFile
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill in the page contents
        // This looks for and fills in asp:ContentPlaceHolder controls based on ID
    }
}

主页:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Standard_Page : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int myID = (this.Page as CMSPageViewer).myPageID;
    }
}

如何从使用的MasterPage中访问ID?

投放页面似乎不起作用。我收到以下错误:

Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)

4 个答案:

答案 0 :(得分:2)

我不喜欢这个设计,但如果应用程序中只有一个页面,那么这开始变得更有意义了。

实际上,这不是母版页的用途。这就是主题的用途。

答案 1 :(得分:2)

在母版页中定义变量。给它适当的吸气剂/孵化剂。在每个页面中调用master.setter并“将变量传递到”母版页。

至少你错了,但这是你必须做的。

引用第5章第255-250页中的“ASP.NET 3.5 Unleashed”http://www.amazon.com/dp/0672330113部分,根据正在解释的Master修改Page属性。

再次,引用ASP.NET 3.5 Unleashed第6章开始:

  

主题与母版页不同。通过母版页,您可以在网站的多个页面之间共享内容。另一方面,主题可以控制内容的外观。

换句话说,你不应该使用母版页作为主题,两者一起工作。

你想让我继续吗?我还有一些其他的书。我已经完成了你想要做的事情(根据内容修改主人),当时我知道这是一个黑客攻击,但我之所以这样做是因为我必须这样做。所以我告诉你的是我所做的,这是有效的。

现在请再次告诉我,我建议不能做什么。我会去找一些更多的参考资料来解释为什么你不能从Master中强制转换为Page。


对于那些希望在我转向一本书以供参考的人时,请注意这就是大男孩们玩耍的方式,这是获得实际合同的人如何玩,而且这是你告诉老板的方式。这是一本书。这就是他们的目的。此外,Stephen Walther不是一个人,他是ASP.NET团队的高级产品经理。所以他知道他到底在说什么。我会听取他的意见。见鬼,我买了他的书不是吗?

答案 2 :(得分:0)

在您的母版页中使用:

(this.Page as CMSPageViewer ).ID

答案 3 :(得分:-2)

您无法使用可以从页面和母版页访问的会话变量。

HttpContext.Current.Session[key] = value;