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

StackOverflow https://stackoverflow.com/questions/9093619

Question

I think I summed up the question in the title. Here is some further elaboration...

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

The web user control has a specific set of JavaScript functions (mostly jQuery code) that are containted within *.js files and automatically inserted into page headers.

However, when I want to use the control more than once on a page, the *.js files are included 'n' number of times and, rightly so, the browser gets confused as to which control it's meant to be executing which function on.

What do I need to do in order to resolve this problem? I've been staring at this all day and I'm at a loss.

All comments greatly appreciated.

Jason

Was it helpful?

Solution

If the issue is simply that the same file is being embedded multiple times and causing conflict, look into using RegisterClientScriptInclude. If you use the same identifier for all of your calls to RegisterClientScriptInclude only one instance of that file will be embedded:

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

However, if the issue is that your methods are being called but they don't know what controls on the page to operate on then you need to figure out how to provide your JS some context. Define a JavaScript object that represents your control on the client-side, and on the server-side emit the call that will instantiate it with the client IDs of the controls you'll be operating on.

OTHER TIPS

We are using CustomValidator to validate User Control. The control works fine until you drop two instances of the Control on the same page, since they reference the exact same JavaScript functions, only one control works. Work around, we appended JavaScript function name with control id.

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

In codebehind, we assinged ClientValidationFunction

CustomValidator1.ClientValidationFunction = "Validate_SAPDepartment" + this.ControlId

This may not be the right approach but it works.

I've had this situation before. You register a separate JavaScript file with the page using the ScriptManager. You can stream this as a resource file embedded into the dll if you wish. Then you only call into the functions from your control.

Otherwise a completely separate jquery file may also work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top