简体   繁体   中英

Referencing External Files from ASP.NET Web Control?

What is the preferred method to reference external files from my ASP.NET web control?

My web control needs to access two external files. One is a CSS file. The other is a JavaScript file.

<link href="<%= VirtualPathUtility.ToAbsolute("~/css/mycss.css") %>" rel="stylesheet" type="text/css" />
<script src="<%= VirtualPathUtility.ToAbsolute("~/scripts/myjs.js") %>" type="text/javascript"></script>

The page could potentially contain multiple instances of my control. Of course, I only want the page to include a single reference to each file.

I looked at the Page.ClientScript properties and methods. But it doesn't appear to have one specifically for CSS.

I also looked at using something like Page.Header.Controls.Add(link) , but this doesn't appear to have direct support for preventing multiple references to the same file.

Is there another option?

Okay, so apparently there is no preferred method for this:

The following seems to be working:

if (!Page.ClientScript.IsClientScriptIncludeRegistered("MyControl.ascx.cs"))
{
    Page.ClientScript.RegisterClientScriptInclude("MyControl.ascx.cs", ResolveClientUrl("~/scripts/myjs.js"));

    HtmlHead head = (HtmlHead)Page.Header;
    HtmlLink link = new HtmlLink();
    link.Attributes.Add("href", "~/css/mycss.css");
    link.Attributes.Add("type", "text/css");
    link.Attributes.Add("rel", "stylesheet");
    head.Controls.Add(link);
}

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