Sunday, September 13, 2009

Accessing properties in code-behind class from java-script

If the code-behind class has a property called MySampleProperty and if it returns a string value, then this is how you can access it in your javascript:

   1: <script type="text/javascript">
   2: function onAppLoad() 
   3: {
   4:    var vSampleProp = '<%=MySampleProperty%>';
   5:    alert(vSampleProp);
   6: }
   7: </script>

Realize, that I am saying “access” and not call. Because, what happens here is while the ASP.Net is building the web-page to send down to the browser, it sees the code inside <%…%>, calls the property, fills in the value and then sends it down to the browser.

If you need to “call” a method on the server then you need to look at web-services. (Basically you will need to use AJAX, to get the server to send your data asynchronously).

No comments: