📜 ⬆️ ⬇️

asp.net: register javascript on page

Usually, when developing ASP.NET pages, only the simplest of them do not consist of a number of user elements (web user control). Very often such elements contain some logic of the client script written mainly in javascript. The problem may begin when the user element needs to include a link to the js file on the page. Sometimes you can see the following solution to a problem:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="controls_WebUserControl" %>

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="OnClick()" />

It looks fine, the code will work. This is probably the first decision that comes to mind. Even experienced programmers can write this way. And it will be a mistake. The thing is that ASP.NET cannot track the included link to the js-file and will add it every time it renders the next element on the page. That is, if your element appears on the page more than once, then the link to some_js.js will appear several times. That, of course, is not good. The correct solution of the problem is concentrated in the mechanism of the class ClientScriptManager and its methods IsClientScriptIncludeRegistered and RegisterClientScriptInclude. Here is the correct solution that uses the new method:
ClientScriptManager clientScript = Page.ClientScript;
Type t = this.GetType();
if (!clientScript.IsClientScriptIncludeRegistered(t, "someScript"))
clientScript.RegisterClientScriptInclude(t, "someScript", ResolveClientUrl("~/js/some_js.js"));

This code should be located in the Page_Load method or where it follows from the logic of your control. Here there is a check for the presence of a registered script, and if it does not exist, then the RegisterClientScriptInclude function registers some_js.js on the page.

PS: the first post, do not swear, if something is wrong with the design.
PPS: Karma has accumulated, moved from the personal blog

')

Source: https://habr.com/ru/post/24729/


All Articles