Saturday, December 12, 2009

Post login form without submit button in ASP.Net MVC

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:

   1: <%
   2:  using (Html.BeginForm("Login", "Login", FormMethod.Post,
   3: new { name = "loginForm", id = "loginForm"}))
   4:    { 
%>
   5:     <input id="username" name="username" type="text" /><br />
   6:     <input id="password" name="password" type="password" />
   7: <%
   8:  } 
%>

One way I tried – is to add hidden submit button in form and add defaultbutton = "loginButton" attribute to the form:

   1: <input type="submit" id="loginButton" name="loginButton"
   2: style="visibility: hidden" />

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:

   1: <script type="text/javascript">
   2:     $(function() {
   3:         $('#username, #password').keypress(function(e) {
   4:             if (e.which == 13) {
   5:                 $('#loginForm').submit();
   6:             }
   7:         });
   8:     });
   9: </script>

After that form is successfully submited to the server after Enter key press and values are passed to the Login action of the controller.

3 comments:

  1. When focus is on UserName field, then it is probably bettet to switch to Password field on pressing Enter button instead of submitting form. (Sure when focus is on Password field, then pressing Enter button should submit the form.)

    ReplyDelete
  2. good to see a good start @hodzanassredin

    ReplyDelete
  3. Vladimir,
    thanks for comment. But this is some kind of implicitly and is not very good. Common user experience is to switch focus by tab and shift-tab keys, and submit form by enter key (thats how gmail works for example)

    ReplyDelete