简体   繁体   English

asp.net 网络表单从用户控制注册 javascript

[英]asp.net webforms registering javascript from user control

I have a abstract user control that provides common functionality across a few controls, it requires some javascript functions to hook up client side events, what is the best way to inject this javascript.我有一个抽象的用户控件,它提供了几个控件的通用功能,它需要一些 javascript 函数来连接客户端事件,注入这个 javascript 的最佳方法是什么。

I did have a look at ScriptManager.RegisterClientScriptBlock but it seems that this is aimed at using UpdatePanels and the like which I am not doing, would this still work correctly if all I want to do is have this javascript located in a single place and rendered from the abstract user control?我确实看过 ScriptManager.RegisterClientScriptBlock 但似乎这是为了使用我没有使用的 UpdatePanels 之类的东西,如果我只想将这个 javascript 放在一个地方并渲染,这是否仍然可以正常工作从抽象的用户控件?

If you are not rendering in an async postback, then use the ClientScriptManager's RegisterClientScriptBlock instead.如果您不在异步回发中呈现,请改用 ClientScriptManager 的RegisterClientScriptBlock You can access this from the Page.ClientScript property.您可以从Page.ClientScript属性访问它。 If you use the ScriptManager's method, it should work, but it would require that the page have a ScriptManager on it in addition to your control.如果您使用 ScriptManager 的方法,它应该可以工作,但是除了您的控件之外,它还需要页面上有一个 ScriptManager。

Another option is to include a javascript file in the page header, like this:另一种选择是在页面 header 中包含 javascript 文件,如下所示:

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

Here is a similar question I found:这是我发现的一个类似问题:

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

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

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