Pregunta

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?

¿Fue útil?

Solución

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top