ASP.NET - 如何仅在尚未包含 CSS 时才包含它?

ASP.NET - How to include CSS only if it isn#39;t already included?(ASP.NET - 如何仅在尚未包含 CSS 时才包含它?)
本文介绍了ASP.NET - 如何仅在尚未包含 CSS 时才包含它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码来动态包含一个 CSS 文件:

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?

告诉我使用 !IsPostBack 包含在页面加载中的答案不会解决我的问题,因为此代码将位于 Web 用户控件中,并且我的页面可能有很多相同的用户控件.

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.

例如,我用下面的代码用javascript来做:

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

推荐答案

做到了...

我使用的代码如下:

        Boolean cssAlrealyIncluded = false;
        HtmlLink linkAtual;
        foreach (Control ctrl in Page.Header.Controls)
        {
            if (ctrl.GetType() == typeof(HtmlLink))
            {
                linkAtual = (HtmlLink)ctrl;

                if (linkAtual.Attributes["href"].Contains("datePicker.css"))
                {
                    cssAlrealyIncluded = true;
                }
            }
        }

        if (!cssAlrealyIncluded)
        {
            HtmlLink link = new HtmlLink();
            link.Attributes.Add("href", ResolveUrl("~/Utilities/datePickerRsx/datePicker.css"));
            link.Attributes.Add("type", "text/css");
            link.Attributes.Add("rel", "stylesheet");
            Page.Header.Controls.Add(link);
        }

这篇关于ASP.NET - 如何仅在尚未包含 CSS 时才包含它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)