简体   繁体   English

在用户按Enter / Return键时调用服务器端操作

[英]Invoke a server side action upon the user pressing the Enter/Return key

Updated 更新

Since I got your very helpful answers to this question so promptly, I have reconsidered the problem. 自从我迅速得到您对这个问题的非常有帮助的答案以来,我已经重新考虑了这个问题。 I think I need to break it down into two small requirements, so I am updating the question. 我认为我需要将其分解为两个小要求,因此我正在更新这个问题。

In my ASP.NET MVC 4 application, I need that when the user presses the enter key on the keyboard while the focus is in a specific textbox: 在我的ASP.NET MVC 4应用程序中,当焦点位于特定文本框中时,当用户按下键盘上的Enter键时,我需要这样做:

Scenario 1: The appropriate server side action must be called. 方案1:必须调用适当的服务器端操作。 If the user presses the enter key when the cursor is in a different text box, another action must be called. 如果用户在光标位于其他文本框中时按Enter键,则必须调用另一个动作。

Scenario 2: If the user pressed the Enter key on the keyboard while the focus is in any textbox in one of the forms on the current page, the form must be posted back with all the form data (HttpPost) to the action on the controller as specified in the action attribute of that <form> . 方案2:如果用户在焦点位于当前页面上任一表单的任何文本框中时按下键盘上的Enter键,则该表单必须与所有表单数据(HttpPost)一起回发到控制器上的操作如该<form>的action属性中所指定。

How do I accomplish these two scenarios? 如何完成这两种情况?

$('#idOfTextbox').keypress(function(e) {
    if(e.which == 13) {
        $.ajax({
        //.. Your values go here...
        });
    }
});

If you want to intercept a submitted form, you can use the ajaxForm plugin . 如果要拦截提交的表单,可以使用ajaxForm插件 This way, you can have several forms on the page and when a form is submitted, it will make an AJAX call to the action method specified in the form's action attribute. 这样,您可以在页面上拥有多个表单,并且在提交表单后,它将对表单的action属性中指定的action方法进行AJAX调用。 You will then be able to handle the response in the 'success' callback of the ajax call. 然后,您将能够在ajax调用的“成功”回调中处理响应。

您可以使用javascript或简单地将每个输入放在不同的<form>并在其中键入type =“ submit”。

element.onkeydown = function(event) {
    //do something on keydown (enter is keyCode === 13)
};

You can do it as below: 您可以按照以下步骤进行操作:

$('#idOfTextbox').keypress(function(e) {
    if(e.which == 13) {
       $.ajax({

       url: './savedata',//Your method name, that is to be called
       type: 'POST',
       contentType: 'application/json',//Type of data you want to post
       data: JSON.stringify({ obj: sampleobject }),//object of post-object i.e. data being posted
       success: function(result) {
       //Logic to handle success
        }  
       error: function(){}//Handle error here  
     }
}); 

I have given an example to call a method that is on the same controller on whose view you are currently working with.. 我举了一个例子来调用一个方法,该方法位于您当前正在使用其视图的同一控制器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM