In web application it is common situation when form should be submitted to server by clicking on Enter key. Recently I needed to add such behavior in ASP.Net MVC application.
There is a login area on top of the master page with 2 textboxes: username and password. These values should be submitted to Login action of LoginController when user press Enter when focus is on one of them:
One way I tried – is to add hidden submit button in form and add defaultbutton = "loginButton" attribute to the form:
But with “visibility: hidden” form was not submitted. When I removed this style everything worked (actually it worked with visible submit button even without defaultbutton = "loginButton" attribute).
Another way which worked for me – is to add keypress handler on textboxes. I added the following jquery script on the page:
After that form is successfully submited to the server after Enter key press and values are passed to the Login action of the controller.