开发者

How do I refer a master page Content control from a User Control?

I have a user control in it I want to 'inject' something into the head of a master page. I have tried to use the following approach (master page and user control mmarkup snippets)...

MasterPage:

<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>

User Control:

<asp:Content I开发者_如何学编程D="Content1" ContentPlaceHolderID="head" runat="server">
    <link type="text/css" rel="stylesheet" href="/Shared/Css/Navigation.css" />
</asp:Content>

But that gives the error:

Content controls have to be top-level controls in a content page or a nested master page that references a master page.

So how do I put content into the master page at runtime from a control?


You can't.

By default data is designed to flow from master to user page, not vice versa.

See Working with ASP.NET Master Pages Programmatically and How Master Pages Work for details.


You can access a master pages content through public methods of the master page. So if I take the example from your question, you can set the link's href in the master page from your user control or page with the following modification of your code:

Introduce the link as "normal content" in the master page and give him an id so that you can access it from code behind.

<link id="link" type="text/css" rel="stylesheet" />

Add a property to the master page that set's the href.

public string LinksHref
{
     get { return link.Href; }
     set { link.Href = value; }
}

If you want to access this from a page you can add a MasterType directive.

<%@ MasterType VirtualPath="~/Site.Master" %>

Change the property in the controls code behind.

Master.LinksHref = "/Shared/Css/Navigation.css";

If you want to access this from a user control, you can't use the MasterType directive and have to do the casting by yourself:

((MasterPageClassName)Page.master).LinksHref= "/Shared/Css/Navigation.css";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜