views:

70

answers:

2

Is it possible for an user control (ascx) to doing something like herit from a MasterPage ?

My point is, in one of my user control (only use by one kind of MasterPage), I would like to use an <asp:content> tag, but I can't, I can only in the page that use that user control...

So, I have to repeat some code into each of the page that use that user control...

Update

For example, each time, I need to add something like that :

<asp:Content ID="cntJavascript" ContentPlaceHolderID="cphJavascript" runat="server">
    <script type="text/javascript" src="<%= Url.Content("~/Content/js/UcJs.js") %>"></script>
</asp:Content>

That because, I want all my Js files on the same place in my MasterPage and I only want to add Js that is needed

A: 

I assume your user controls output the javascript url which is different for each user control. There are a couple ways I can think of to do this.

Add a method in your masterpage like:

void AddJavascriptFile(string url) {
    this.ContentPlaceHolder1.Controls.Add(
        new LiteralControl(
            "<script type='text/javascript' src='" + url + "'></script>"));
}

...then in your user control you can add your javascript like so:

((MyMasterPage)((System.Web.UI.Page)this.Parent).Master).AddJavascriptFile(
    "http://example.com/javascript.js");

This might point you in the right direction - I'm still not entirely sure what you're trying to do.

BuildStarted
+1  A: 

I think the answer you're looking for is to use Page.RegisterClientScriptInclude in each of the controls that require the supporting Javascript code, using the same key value each time.

In this way, the Javascript file will be included only once no matter how many controls require it.

internal static void RegisterJavascriptInclude(Page page, string includeFile)
{
    string key = includeFile.ToLowerInvariant();

    if (!page.ClientScript.IsClientScriptIncludeRegistered(key))
        page.ClientScript.RegisterClientScriptInclude(key, page.ResolveClientUrl(includeFile));
}
Ed Courtenay