简体   繁体   English

ASP.NET:在后面的代码中更改CSS链接href?

[英]ASP.NET: Change the CSS link href in code hehind?

I have an .ASPX page in which I want to change the CSS href in code behind. 我有一个.ASPX页面,我想在其中更改后面代码中的CSS href。 I searched for several tricks to do this but couldn't find anything that works as I intend. 我搜索了一些技巧来做到这一点,但找不到符合我预期的任何方法。

HTML Markup: HTML标记:

<link id="linkCSS" runat="server" href='/css/1.css' rel="stylesheet" type="text/css" />

This is what I attempted in Code behind: 这是我在代码背后尝试的方法

If (mobile)
{
    HtmlLink link = (HtmlLink)this.FindControl(linkCSS.UniqueID);
    link.Href = "/css/2.css";
}

But I'm getting the following exception: 但是我收到以下异常:

Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlGenericControl' to type 'System.Web.UI.HtmlControls.HtmlLink'. 无法将类型为“ System.Web.UI.HtmlControls.HtmlGenericControl”的对象转换为类型为“ System.Web.UI.HtmlControls.HtmlLink”的对象。

Any ideas? 有任何想法吗? Thanks. 谢谢。

Since you can't get and modify the control (although I believe it's possible) you can use placeholder to have more control over it. 由于您无法获取和修改控件(尽管我相信有可能),因此可以使用占位符来对其进行更多控制。 Like this: 像这样:

<asp:PlaceHolder ID="headPlaceHolder" runat="server" />

And then in your server code: 然后在您的服务器代码中:

HtmlLink link = new HtmlLink();
link.Href = "/css/2.css";
headPlaceHolder.Controls.Add(link);

See if it helps :) 看看是否有帮助:)

There is no need to find css you can change it as follows. 无需查找css,您可以按以下方式进行更改。

If (mobile)
{
  linkCSS.Attributes["href"] = "~/css/2.css";
}

I've had reffered This Link. 我已经引用了此链接。

You can use this code on your server side 您可以在服务器端使用此代码

HtmlGenericControl link = this.FindControl(linkCSS.UniqueID) as HtmlGenericControl;

link.Attributes["href"] = "css/2.css";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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