简体   繁体   中英

Asp.Net - UserControl - Inherit from MasterPage

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

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));
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM