Raising javascript events from an ASP.NET user control and processing on an ASP.NET page

On an ASP.NET page, I have a user control and I want to perform some actions inside it using javascript. When this action is complete, I want to raise an event (again in javascript) that will be raised using the ASP.NET page (again in javascript).

The reason I want to do this is because I have several user controls on the page and I need an action to be performed in one user control in order to instantiate the action in another user control without doing a postback .

Does anyone know how to do this?

Thank you very much.


Hi and thanks for the reply. What I'm trying to do is create some form of encapsulation. Therefore, if javascript code does something in one user control, the user control should not be aware of the effect of else where. This would trigger an event in javascript that could be caught using javascript created using the asp.net page, which in turn can call the javascript method in another user control, if necessary. The idea here is also to eliminate any need for postback.

Hope it will be better.

+4
source share
2 answers

I think an easy way to implement what you are describing is to forget about JavaScript events and just provide a β€œcallback” function for custom controls.

The way I implement it is to open a public property in a user control that takes the name of this JavaScript callback function. The user control is then responsible for calling this function after it has completed work on the client side.

Thus, a page using user controls will need to implement this JavaScript callback function and then provide the name in the properties to the user controls.

Has the meaning?

+6
source

You can simply run the javascript you need from the display HTML of your user control.

 <a href="javascript:doSomething();">Click Me</a> 

From the sounds of things you want to create some form of controller in JavaScript. When the page loads each of your control registers by the controller. Then the action in one of your controls performs a function on the controller, which does something with the controls registered with it.

Your JavaScript may be as simple as:

 var oControls = new Array(); 

doSomething = function () {for (var i = 0; i <oControls.length; i ++) {var oControl = document.getElementById (oControls [i]); oControl ......}}

So, you need to register your control using the ScriptManager in the method of rendering your users.

 ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Startup", String.Format("oControls.push('{0}');", ClientID), True); 
0
source

All Articles