Wednesday, December 5, 2007

How to run serverside code from client side script

In the last article, we saw how to access server side control values on the client side. However, an even more interesting (and lesser known) mechanism in Asp.Net is running server side code in client side script. This can come in very handy in some situations, as we'll see through the following example. Suppose we need to create a graphical representation of some quantity. Let us say we have two variables on the server side, a [barCount] variable, to indicate the value to be shown on the graph, and a maxCount variable, that determines the maximum value that can be shown in the graph. To give you an idea of what I'm talking about, look at the following screenshot: The variables [maxCount] and [barCount] are serverside variables in your C# code behind file. Note that they have to be made public. maxCount is the total number of bars on the graph, while barCount gives the actual value to be represented on the graph. How did we do it ? One way, of course, is to use a repeater control, and modify it to render the required output. We are not particularly in favor of this approach, because a repeater is more conducive to databinding kind of functionality, not the one we are discussing here. Instead, here's the code we used :

<form id="form1" runat="server">
You Entered :
<br />
maxCount = <%=maxCount %>
<br />
barCount = <%=barCount %>
<table width="100%">
<%for(int i = 0; i < maxCount; i++ ) %>
               <%{ %>
                  <%  if( i <= barCount )  %>
<%  { %>
<td style="border-right: #000000 1px solid; border-top: #000000 1px solid; border-left: #000000 1px solid;
color: #6600ff; border-bottom: #000000 1px solid; background-color: #0000cc;">
<% }%>
<% else%>
<%  { %>
<td style="border-right: #000000 1px solid; border-top: #000000 1px solid; border-left: #000000 1px solid;
border-bottom: #000000 1px solid;">
<%  }%>
<%} %>
Recall that the blocks are used to emit server side code on the client side. What is happening here is that when the Page HTML is being generated, the [for] loop code gets executed. Since we declared barCount & maxCount as public variables, these are accessible in the code block. Depending on these values, an appropriate number of elements are inserted in the code, which eventually gives us the output graph. Please note that the script blocks are executed during the [RENDER] phase of the page. It means that if you are setting the variable values multiple times during your page lifecycle, the value set just prior to Render will be used. Keep in mind the following points about client code blocks :  This mechanism was put in place for backward compatibility with ASP.  Only public variables / properties / methods are accessible in the client code blocks.  Should be used only where appropriate. Check out the actual source code here. View the running application here. Happy Coding !!

No comments: