Does a MasterPage know what page is being displaye

2019-04-06 09:57发布

When I navigate on a website utilizing MasterPages, does the application know what page I am on? If so, does it store it in an object I can access?

The reason I am asking is so I can replace this:

//masterpage 
<div id="nav_main">
   <ul><asp:ContentPlaceHolder ID="navigation" runat="server">                    
   </asp:ContentPlaceHolder></ul>
</div>

//content page(s)
<asp:Content ContentPlaceHolderID="navigation" ID="theNav" runat="server">
   <li><a href="default.aspx">Home</a></li>
   <li id="current"><a href="faq.aspx">FAQ</a></li>
   <li><a href="videos.aspx">Videos</a></li>
   <li><a href="#">Button 4</a></li>
   <li><a href="#">Button 5</a></li>
</asp:Content>

With a more elegant solution for the navigation, which highlights the link to the page by having the list item's ID set to "current". Currently each page recreates the navigation with its respective link's ID set to current.

12条回答
走好不送
2楼-- · 2019-04-06 10:19

To get the current request URL from within the master page you would do:

string s = this.Page.Request.FilePath; // "/Default.aspx"

I also recommend moving your navigation into the master page instead of the content page. This will make it easier to maintain / access.

查看更多
冷血范
3楼-- · 2019-04-06 10:19

The navigation control, not the master page, should be in charge of what page is currently highlighted.

Either the page that is loaded should notify the navigation item who it is, or the nav control itself should keep track of it.

The point is that master pages are supposed to simply be a holder that content is displayed in. They aren't supposed to control anything.

查看更多
狗以群分
4楼-- · 2019-04-06 10:23

You should be able to get the page by accessing the Page property. IE:

string type = this.Page.GetType().Name.ToString();
查看更多
ら.Afraid
5楼-- · 2019-04-06 10:25

You'd probably just use one of the Request path from within the master page to set the current. I'd probably also have a property on the master page to override it, so that pages without links or something could set it to something reasonable.

查看更多
姐就是有狂的资本
6楼-- · 2019-04-06 10:26

There's also the Request.RawURL

查看更多
smile是对你的礼貌
7楼-- · 2019-04-06 10:27

Yes, Use the below code in your master file. It will give you the content page name.

Page.ToString().Replace("ASP.","").Replace("_",".")
查看更多
登录 后发表回答