如果你想从客户端做一个服务器端调用,您需要使用一些JavaScript来发起回发,或者对您的应用程序执行AJAX调用。
首先,您需要处理您的按键。 jQuery提供方便keypress
方法来捕获一个元素上的按键:
$("#mytextbox").keypress(function(e){
// Use e.which, etc to find out which key was pressed.
});
不幸的是,功能键(F1-F12)需要在某些浏览器,他们不产生keypress
事件特殊处理。要在所有现代浏览器中可靠地捕获功能键,您必须查看使用keydown
和keyup
事件。我建议你阅读this article以了解如何解释您所支持的浏览器中的关键事件。
接下来,您需要创建一个ASP.NET Web方法。做到这一点的方法是创建网页上的某公共静态方法(或一个单独的页面,如果你喜欢),然后用WebMethodAttribute属性装饰它:
[WebMethod]
public static string MyMethod(int foo, int bar, string bob)
{
return "Welcome to The World of Tomorrow!";
}
最后,你可以使用jQuery调用此方法并做一些与响应:
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);
}
}
}
});
在成功调用,这个代码点点就会显示警告“欢迎来到未来世界!”,传递到浏览器从ASP.NET的响应方法。
简短的回答是,你问的是完全可能的,但它不像你想像的那么简单。检测按键的麻烦特别麻烦。祝你好运!
F5被浏览器用来刷新! – 2009-08-28 20:17:03
是的,我知道并注意到 - 但为什么我不能捕捉F12 ??这不是用于浏览器的任何事情,默认情况下..... – 2009-08-28 21:26:35