ASP.NET Web User Control with Javascript used multiple times on a page - How to get javascript functions to specify the correct controls

I think I summed up the question in the title. Here is another development ...

I have a web user control that is used in several places, sometimes more than once on a given page.

The web user control has a certain set of JavaScript functions (mostly jQuery code) that are contained in * .js files and are automatically inserted in the page headers.

However, when I want to use the control more than once on the page, the * .js files are included in the number "n" times and, true, the browser gets confused as to which control it should execute which works.

What do I need to do to solve this problem? I look at it all day, and I'm at a loss.

All comments were greatly appreciated.

Jason

+4
source share
3 answers

If the problem is that the same file is embedded several times and causes a conflict, consider using RegisterClientScriptInclude . If you use the same identifier for all your calls in RegisterClientScriptInclude, only one instance of this file will be embedded:

http://msdn.microsoft.com/en-us/library/2552td66.aspx

However, if the problem is that you are calling your methods, but they don’t know which controls on this page are working, you need to figure out how to give your JS some context. Define the JavaScript object that represents your control on the client side, and on the server side emits a call that will create it with the client IDs of the controls you will be working on.

+4
source

We use CustomValidator to test user control. The control works fine until you drop two instances of the control on the same page, since they link to the same JavaScript functions, only one control works. While working, we added the name of the JavaScript function with the control identifier.

 Validate_SAPDepartment<% =ControlId %>(oSrc, args) {...} 

At Codebehind, we rated ClientValidationFunction

 CustomValidator1.ClientValidationFunction = "Validate_SAPDepartment" + this.ControlId 

This may not be the right approach, but it works.

+1
source

I had this situation before. You register a separate JavaScript file with the page using ScriptManager. You can pass this as a resource file embedded in the dll if you want. Then you only call functions from your control.

Otherwise, a separate jquery file may work.

0
source

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


All Articles