The Disturbed Buddha

Simple Observations of a Self-proclaimed Novice

Executing Server-side Code from JavaScript

In the Asp.net forums, I often see the question asked, “Can I call server-side code from the client/JavaScript?” Almost invariably, the responses given are “No, the client cannot access the server,” or “You can only use WebMethods or PageMethods.” The first response is not entirely correct, and unfortunately, WebMethods and PageMethods are static methods and therefore have no way to directly access the page.

This is why I present to you the following “hack”. I call it a hack because there really should be some way built into the ASP.NET AJAX Extensions that allow this approach directly. Instead, it relies on using controls in a manner that they aren’t necessarily intended in order to obtain the desired result. But this “hack” does have a redeeming quality—it’s incredibly easy.

The Code:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>         

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
  <title>My Page</title> 
  <script type="text/javascript"> 
    function myClientButton_onclick() { 
    document.getElementById('myServerButton').click(); 
  } 
  </script> 
  <script runat="server"> 
    Protected Sub myServerButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles myServerButton.Click 
      Response.Redirect("http://www.asp.net/") 
    End Sub 
  </script> 
</head> 
<body> 
  <form id="form1" runat="server"> 
    <input id="myClientButton" type="button" value="Press Me" onclick="return myClientButton_onclick()" /> 
    <asp:Button ID="myServerButton" runat="server" style="display:none;" /> 
  </form> 
</body> 
</html>

Explanation:

What I am doing here is adding a server-side button control (<asp:Button runat=”server” …>). I then make the button invisible by adding style=”display:none;”. In the button’s server-side Click event, I do whatever it is I want to do on the server.

In this example, I am clicking a standard client-side button (<input type=”button” …>) to fire off a server-side redirect, but this could just as easily be called by selecting an item in a DropDownList, typing text into a textbox, etc. Clicking the client button calls the JavaScript .click() event of the server-side button control.

The Next Step:

“What if I need to pass arguments from the client-side script to the server-side script?” Well, this is easily done by putting server-side HiddenField controls on the page. Use the JavaScript to set their values (document.getElementById(‘myHiddenField’).value = “Hello World”;) and then use C# or VB.NET to retrieve them on the server (Dim myVar as String = myHiddenField.Value).

In my next article, I will apply this concept to create a rather easy approach to the Ajax Multi-Stage Download Pattern. Check back soon!

Tested on: Internet Explorer 7, Netscape Browser 8, Firefox 2, Safari 3, Opera 9.

About these ads

January 8, 2008 - Posted by | Ajax, ASP.NET, Javascript, Web Development

23 Comments »

  1. Thanx a lot

    Comment by Beloded Evgenij | March 3, 2008 | Reply

  2. A tidy little hack… works like a dream!

    Comment by Tom John | April 8, 2008 | Reply

  3. this is very simple . thank you very much

    Comment by raman | April 9, 2008 | Reply

  4. Hi, i from Kuala Lumpur, Malaysia.
    Thanks a lot cause this articles was helped me in my current project.

    Comment by RaoNet | April 23, 2008 | Reply

  5. Thank you. You rule.

    Comment by johann Botha | May 23, 2008 | Reply

  6. It’s Beautiful. Awsome.

    Comment by Syed | June 20, 2008 | Reply

  7. Simply very smart. I loved the work around.

    Comment by Serious Dilemma | November 9, 2008 | Reply

  8. nice one!

    Comment by jeff | March 27, 2009 | Reply

  9. I don’t think people that ask the question above truly understand how client-server paradigm works on the web. Your example is a workaround to allow controls to invoke a postback. This does not mean javascript is invoking server-side logic directly. I think it’s a bit misleading here.

    Comment by Roman | September 3, 2009 | Reply

  10. Excellent Hack.

    Bookmarked here in codebounce.com:
    http://www.codebounce.com/ASPNET/Executing-Server-side-Code-from-JavaScript

    Comment by Tom G | October 23, 2009 | Reply

  11. Thank you boss…….
    You are simply great…….
    After looking aorund so many different things, this is the one I was looking for…..
    Thanks again…. Long live Bhuddha…..

    Comment by hitesh | March 16, 2010 | Reply

  12. Good stuff…!

    Comment by Ashish | April 21, 2010 | Reply

  13. Great Solution,

    thanks, your code saved alot of my time…

    Comment by Ratnakar | May 3, 2010 | Reply

  14. Wonderfull.

    Comment by Abhishek Dhanotia | March 23, 2011 | Reply

  15. thanks a lot…it really worked.

    Comment by Tara | April 21, 2011 | Reply

  16. thanks a lot. i was searching the technique.it does a lot

    Comment by Joel Lyte | May 27, 2011 | Reply

  17. simply amazing m8 tnx alot, you made my day

    Comment by seryigsSergop | December 31, 2011 | Reply

  18. This is awesome

    Comment by Bobby | June 8, 2012 | Reply

  19. thanks a lot!!!

    Comment by sarika | July 12, 2012 | Reply

  20. Great work, it help me alot. Many thanks

    Comment by Zahoor Ahmad | December 8, 2012 | Reply

  21. Very good blog! Do you have any hints for aspiring writers?
    I’m hoping to start my own blog soon but I’m
    a little lost on everything. Would you suggest starting
    with a free platform like WordPress or go for a paid option?
    There are so many options out there that I’m totally overwhelmed .. Any tips? Kudos!

    Comment by psn code generator | December 28, 2012 | Reply

  22. What’s up to every body, it’s my first pay a visit of this blog; this
    webpage carries awesome and in fact good data for
    visitors.

    Comment by caroleglein.bcz.com | March 30, 2013 | Reply

  23. Thanks… :) Good job..

    Comment by Edwin Gabriel Bobadilla | June 9, 2013 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: