Thursday, March 4, 2010

Post Server Side without Postback

I was reading from the following article:

http://disturbedbuddha.wordpress.com/2008/01/08/executing-server-side-code-from-javascript/

and realized that this opened up some possibilities for me. Hopefully it can for you as well.
It discusses the use of combining both Javascript and Server-Side Code. I took his example a step further.
Lets say that you want to validate a user form, but you don't want to have a postback to the server during the validation. Javascript would be the preference here, and it could look similar to the following:

if
(document.formname.elementname.value == "") {
var results = document.getElementById('resultslabel');
results.innerHTML = ("Please put in a name.");
return false;
}

and the control to validate would simply be a standard html button:

<input type=button onclick=formCheck(); value=Submit />

However, let's say that you want to include a server-side event after the validation is complete. I tried first to simply add a onserverclick event handler to the button, but it posted back everytime regardless of the client status. I tried using an Update Panel, with a standard asp.net button control, same thing. This hack solved the trick. I added an ASP.NET Button, called it Button2, such as:

<asp:Button ID=Button2 runat=server style=display:none; onclick=Button2_Click />
(note the style tag...), and added a Server-side event handler to Button2.

Now, simply add the line:

document.getElementByID('Button2').click();

after the if condition in your javascript code.
Easier than I thought...

0 comments: