views:

31

answers:

2

I have an asp button (the code is below). I have the event handler working, but I want to pass a string (which is the result of a javascript function) into the event handler function. Is there a way to do that?

<asp:Button runat="server" ID="Button1"  OnClick="Button1_Click" Text="Run" />
+1  A: 

Not in the way you're asking.. However...

You CAN add an ASP:HiddenField, and use Javascript to modify the value of the HiddenField to be your string. Then you can access this in your Button Click event.

An example can be found here.

David Stratton
is there a way to run the javascript function when the button is pressed?
jamesatha
Yes, see here: http://msdn.microsoft.com/en-us/library/aa479011.aspx
David Stratton
+1  A: 

Normally the way you would do this is to have you javascript modify an input control so that the value will be posted back with the Button click. If you want the user to visually not be able see the data that your javascript is modifying to post back then you can write it to a HiddenField.

You can use the OnClientClick to setup the javascript to run before the postback happens to ensure your modified value is put into the input control. Eg:

<asp:Button ID="yourButton" runat="server" Text="Click Me!"
    OnClientClick="YourFunctionToAddStringToControl(); return true;"
    OnClick="yourButton_Click" />

So you just need to swap the call to YourFunctionToAddStringToControl with your modified javascript function that is writing the value to a HiddenField or another input control. Then update your server side click handler to access the field.

Side Note: When using javascript to write to server side controls such as HiddenField, don't forget to use <%= yourHiddenField.ClientID %> to get the correct control name.

Kelsey