以编程方式将 Javascript 文件添加到 .net 中的用户控件 [英] Programmatically adding Javascript File to User Control in .net

查看:17
本文介绍了以编程方式将 Javascript 文件添加到 .net 中的用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式将 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".

这篇关于以编程方式将 Javascript 文件添加到 .net 中的用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆