我正在母版页上编写代码,我需要知道正在显示哪个子(内容)页面。如何以编程方式执行此操作?
16 回答
我用这个:
string pageName = this.ContentPlaceHolder1.Page.GetType().FullName;
它以这种格式“ASP.default_aspx”重新调整类名,但我发现对于大多数用途来说这很容易解析。
希望有帮助!
最好让ContentPage
通知MasterPage
。这就是为什么ContentPage
有一个Master
属性而MasterPage
没有Child
属性。最好的做法是在 上定义一个属性或方法,并MasterPage
通过.Master
ContentPage
如果您使用此技术,最好明确指定 MasterPage 的类名。这使得在 ContentPage 中使用 MasterPage。
例子:
//Page_Load
MyMaster m = (MyMaster)this.Master;
m.TellMasterWhoIAm(this);
希望这可以帮助。
这听起来像是一个坏主意。大师的想法是它不应该关心那里的页面,因为这是每个页面的所有通用代码。
我有理由检查母版页中的子页。
我的母版页上有所有菜单选项,如果未设置某些系统设置,则需要禁用它们。
如果不是,则会显示一条消息并禁用按钮。由于设置页面是此母版页的内容页面,我不希望该消息继续显示在所有设置页面上。
这段代码对我有用:
//Only show the message if on the dashboard (first page after login)
if (this.ContentPlaceHolder1.Page is Dashboard)
{
//Show modal message box
mmb.Show("Warning Message");
}
使用下面的代码。
Page.ToString().Replace("ASP.","").Replace("_",".")
这是我对问题的解决方案(此代码进入母版页后面的代码):
if (Page.TemplateControl.AppRelativeVirtualPath == "~/YourPageName.aspx")
{
// your code here
}
或者更复杂一点,但可读性较差:
if (Page.TemplateControl.AppRelativeVirtualPath.Equals("~/YourPageName.aspx", StringComparison.OrdinalIgnoreCase))
{
// your code here
}
Request.CurrentExecutionFilePath;
或者
Request.AppRelativeCurrentExecutionFilePath;
我在我的一个项目中做了类似的事情,以根据正在加载的页面动态附加 css 文件。我只是从请求中获取文件的名称:
this.Request.Url.AbsolutePath
然后从那里提取文件名。我不确定如果您正在重写 URL,这是否会起作用。
您可以通过获取最后一个段或请求来做到这一点,我将成为表单名称
string pageName = this.Request.Url.Segments.Last();
if (pageName.Contains("EmployeeTermination.aspx"))
{
}
你可以试试这个:
<%: this.ContentPlaceHolder1.Page.GetType().Name.Split('_')[0].ToUpper() %>
将该代码title
放在Site.Master
string s = Page.ToString().Replace("ASP.directory_name_","").Replace("_aspx",".aspx").Replace("_","-");
if (s == "default.aspx")
{ /* do something */ }
我正在使用这么多答案
<%if(this.MainContent.Page.Title != "mypagetitle") { %>
<%}%>
这使得排除任何单个页面变得容易,并且由于您比较一个字符串,您甚至可以为 exclude_pagetitle 之类的页面添加前缀并比较标题的子字符串。我通常使用它来从某些我不想加载的功能中排除登录页面,例如会话超时和实时聊天。
下面的代码就像一个迷人的..试试看
string PName = Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1];
您应该可以从母版页代码中获得 Page.Request.Url.PathAndQuery 或 Url Uri 对象的其他属性之一。
您可以在代码隐藏中检查页面类型:
// Assuming MyPage1, MyPage2, and MyPage3 are the class names in your aspx.cs files:
if (this.Page is MyPage1)
{
// do MyPage1 specific stuff
}
else if (this.Page is MyPage2)
{
// do MyPage2 specific stuff
}
else if (this.Page is MyPage3)
{
// do MyPage3 specific stuff
}