Reputation: 754328
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?
Upvotes: 3
Views: 15302
Reputation: 3760
You just get the client id of the ASP.NET textbox in jquery. Then call ajax through jquery like following.
var aspTextBox = $("#<%=Me.TextBox1.ClientId%>");
aspTextBox.keypress(function(e){
//Code for $.ajax request
if(e.which==13){
$.ajax({
type:"POST",
url:"WebService.asmx/GetData",
contentType:"application/json;charset=utf-8",
dataType:"json",
data:"{}",
success:function(data){
},
error:function(a,b,c){
},
});
}
});
Upvotes: 0
Reputation: 39615
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.
Upvotes: 1
Reputation: 39615
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!
Upvotes: 3
Reputation: 187030
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');
}
});
Upvotes: 2