views:

1437

answers:

3

Is there an easy wayt o capture a keypress (in my case: F5) in a ASP.NET textbox, and executing a server method as a response?

I've created a simple SQL frontend, and out of habit (from SQL Server Mgmt Studio), I keep pressing F5 when I'm done typing my query, but that always refreshes the browser, instead of executing my SQL query :-)

Can I do this in ASP.NET using possibly some Javascript or jQuery ?

Marc

UPDATE:

I have this jQuery code on my ASP.NET page:

 $(document).ready(function() {
    $("#<%= txtQuery.ClientID %>").keydown( function (e) {
        if (e.keycode == 116) {
           $("#<%= btnExecute.ClientID %>").trigger('click');
        }
    });
 });

I tried various combinations of "e.which", "e.keycode" and various values for keycode - but none seem to work. I'm using MS IE 7 on my dev machine. txtQuery is the ASP.NET textbox where I type my query, and btnExecute is the ASP.NET button which will send that query to SQL Server to be executed.

Any ideas? Do I need to suppress the standard event handling somehow? And if so: then how do I accomplish that?

+1  A: 

See keypress( fn )

$("#yourtextboxId").keypress( function (e) {
   // do stuff here
});

and

e.which

will identify the key pressed and I think the keycode for F5 is 116

For triggering an event you can use the

trigger method

$("#yourexecutescriptbutton").trigger('click');

Edit:

If you need to catch F5 then give a keydown event handler

$("#yourtextboxId").keydown( function (e) {
        if ( e.which === 116 )
        {
            $("#yourexecutescriptbutton").trigger('click');  
        }
    });
rahul
OK, so how do I get the jQuery to "click" on my "execute script" button so that the server-side method is executed?
marc_s
replace "// do stuff here" with an AJAX call to the server if the key that was pressed is F5
Jeff Tucker
Doesn't seem to work - F5 still refreshes the browser, and using e.which == 123 for F12 doesn't do anything at all :-(
marc_s
+1  A: 

If you want to do a server-side call from the client, you'll either need to use some javascript to initiate a postback, or perform an AJAX call to your application.

First of all, you need to handle your key presses. jQuery provides the convenient keypress method to capture key presses on an element:

$("#mytextbox").keypress(function(e){
    // Use e.which, etc to find out which key was pressed.
});

Unfortunately, the Function keys (F1-F12) need special treatment in certain browsers where they do not generate keypress events. To capture function keys reliably across all modern browsers, you'll have to look at using keydown and keyup events. I suggest you read this article to understand how to interpret the key events in the browsers you are supporting.

Next, you'll need to create a ASP.NET web method. The way to do this is to create a public static method on your page (or a separate page if you like), then decorate it with the WebMethodAttribute attribute:

[WebMethod]
public static string MyMethod(int foo, int bar, string bob)
{
    return "Welcome to The World of Tomorrow!";
}

Lastly, you can use jQuery to call this method and do something with the response:

var request = $.ajax({
    type: "POST",
    url: "MyPage.aspx/MyWebMethod",
    data: "{ foo:22, bar:19, bob:'A string' }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        var response = null;

        if (typeof (msg.d) != 'undefined')
            response = msg.d;

        if (response == null)
            Error('Message returned by ASP.NET AJAX call is not in the expected format.');

        alert(response);
        },
    error: function(request, textStatus, errorThrown) {

        if (console && typeof console.log != "undefined") {

            try {
                var result = eval("(" + request.responseText + ")");

                if (result && typeof result.Message != "undefined")
                    console.log(result.ExceptionType + ": " + result.Message + "\n" + result.StackTrace);
            }
            catch (ex) {
                console.log(request.responseText);
            }
        }
    }
});

On a successful call, this little bit of code will display an alert "Welcome to The World of Tomorrow!", passed to the browser as a response from the ASP.NET method.

The short answer is that what you ask is entirely possible, however it is not as simple as you might imagine. The hassle over detecting key presses can be particularly troublesome. Good luck!

Programming Hero
yeah, I noticed! :-) I can't seem to reliably catch the keypress - no matter which key I use (on IE 7).... hmm.....
marc_s
+1  A: 

To supress the default behaviour of an event, you have to stop it bubbling up to higher elements. To do this, simply return false from your event handler:

$("#yourtextboxId").keydown( function (e) {
    if ( e.which === 116 )
    {
        $("#yourexecutescriptbutton").trigger('click');
        return false; // Stops keydown event being bubbled.  
    }
});

Unfortunately, depending on how the browser interprets the function keys, it may require preventing keydown and keyup events being raised for that particular key in addition to the behaviour here.

Programming Hero
I have now caught both the `keydown` **and** `keyup` events in MS IE 7, and tried both `e.which` and `e.keycode` - to no avail :-( Guess I'll have get used to not pressing F5 in the browser SQL query window :-(
marc_s