ASP.NET - 如何仅在尚未包含 CSS 的情况下包含 CSS?
我使用下面的代码动态包含 CSS 文件:
HtmlHead head = (HtmlHead)Page.Header;
HtmlLink link = new HtmlLink();
link.Attributes.Add("href", Page.ResolveClientUrl("~/App_Themes/Default/StyleSheet.css"));
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
head.Controls.Add(link);
问题是:我只想执行一次,并且仅当它尚未包含在页面中时才执行。
如何验证它是否已包含在内?
编辑:
告诉我使用 !IsPostBack
包含在页面加载中的答案不会解决我的问题,因为此代码将位于 Web 用户控件内,并且我的页面可能有很多相同的用户控件。
例如,我使用下面的代码通过 javascript 来完成此操作:
if (!Page.ClientScript.IsClientScriptIncludeRegistered("jsScript"))
{
Page.ClientScript.RegisterClientScriptInclude("jsScript", ResolveUrl("~/Utilities/myScript.js"));
}
I use the code bellow to dynamically include a CSS file:
HtmlHead head = (HtmlHead)Page.Header;
HtmlLink link = new HtmlLink();
link.Attributes.Add("href", Page.ResolveClientUrl("~/App_Themes/Default/StyleSheet.css"));
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
head.Controls.Add(link);
The problem is: I want to do it only once, and only if it isn't alrealy included in the page.
How do I verify if it is already included?
Edit:
Answers telling me to include in page load using !IsPostBack
won't solve my problem, as this code will be inside a Web User Control and my page may have a lot of the same user control.
For example, I use the code below to do it with javascript:
if (!Page.ClientScript.IsClientScriptIncludeRegistered("jsScript"))
{
Page.ClientScript.RegisterClientScriptInclude("jsScript", ResolveUrl("~/Utilities/myScript.js"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是吗...
我使用的代码如下:
Did it...
the code I used is as follows:
为什么不在您的用户控件中向 HttpContext.Current.Items 添加一个值,指示样式表已包含在内?这将防止您需要查看用户控件的每个实例的每个标头控件。
Why not in your user control, add a value to HttpContext.Current.Items indicating that the stylesheet has already been included? This will prevent you from needing to look at every header control for every instance of the user control.
在大多数情况下,您不应该关心 CSS 是否被多次包含。这通常不是问题。
编辑:仅当您需要能够覆盖后续样式表中的CSS样式时,顺序才重要。
在 ASP.NET 中,您可以在母版页中包含 CSS(假设您有一个),然后保证只包含一次。由于母版页可以通过编程方式获得(甚至可以从用户控件中获得),因此您甚至可以编写一些属性(或方法)来控制何时包含哪些 CSS 外部内容。
In most cases you shouldn't care if CSS gets included more than once. It's generally not a problem.
EDIT: Order only matters if you need to be able to override css styles in subsequent style sheets.
In ASP.NET, you can include the CSS in your masterpage (assuming you have one) and then it will be guaranteed to only be included once. Since masterpages are available programmatically (even from user controls), you could even write some properties (or methods) that allow you to control which CSS externals to include when.