以编程方式将 Javascript 文件添加到 .net 中的用户控件控件、方式、文件、用户

2023-09-07 15:03:26 作者:頹廢の豬

如何以编程方式将 Javascript 文件添加到用户控件?

How do you add Javascript file programmatically to the user control?

我希望用户控件是一个完整的包 - 即我不想在使用它的页面上添加与用户控件相关的 javascript,因为我可以在控件本身内部执行它.

I want the user control to be a complete package - ie I don't want to have to add javascript that's related to the user control on the page where it's used, when I can do it inside the control itself.

既然用户控件中没有Page对象,你会怎么做呢?

Since there is no Page object in the user control, how would you do it?

推荐答案

在control.ascx.cs文件的Page_Load方法中:

In the Page_Load method of control.ascx.cs file:

LiteralControl jsResource = new LiteralControl();
jsResource.Text = "<script type="text/javascript" src="js/mini-template-control.js"></script>";
Page.Header.Controls.Add(jsResource);

HtmlLink stylesLink = new HtmlLink();
stylesLink.Attributes["rel"] = "stylesheet";
stylesLink.Attributes["type"] = "text/css";
stylesLink.Href = "css/mini-template-control.css";
Page.Header.Controls.Add(stylesLink);

这会将css和Javascript加载到主页的head标签中,只要确保head有runat="server".

This will load css and Javascript into the head tag of the main page, just make sure that the head has runat="server".