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!