I have a web application that will need to access code behind methods as well as javascript methods. For this particular implementation it doesn’t really matter which order they are called in from a program flow perspective.
I’m looking for insight into when it would be appropriate to use a code behind to call javascript and when it would be appropriate to call javascript from a code behind. Are there any ramifications of doing it one way or the other that I should be aware of before moving forward with an implementation?
Is there a best practice way to do it or is it very specific to the actual implementation?
Let’s talk about calling Server side code from JavaScript. This is performed by using Ajax. You can call web methods in the web services and you can also call Page Methods if you decorate them with special attributes.
The main reason of calling server side from js is for using ajax functionality.
Calling js from server side is basically when you inject javascript code into the page and then the client code will be invoked on some action.
UPDATE:
There might be some other reasons also where you need to invoke server side from javascript this can include manually submitting the form using document.form.submit(). But I would say that most of the time 90%+ you call server side code to perform an action asynchronously using ajax.
For second scenario a common example can be when you want to add a confirmation boxes into the buttons that are contained inside the gridview control. In that scenario you will add code in the databound event of the gridview control and add javascript code to the buttons contained in the gridview. Finally, when the gridview is rendered the buttons inside the gridview will have javascript attached to them and when the user clicks the button it pops up the confirmation box. Another scenario can be when you want to open a new popup window after the postback happens.