ASP.NET MVC : Submit Form using Enter Key
Sometimes there is a scenario or requirement of posting the form on pressing the "Enter" key in asp.net mvc. This functionality can be achieved via jQuery in MVC.
Create a "HomeController" with an action method "Index_submit()"
using System.Web.Mvc;
namespace Demo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index_submit() //Get
{
return View();
}
[HttpPost]
public ActionResult Index_submit(FormCollection collection) //Post
{
string name = Request.Form["name"];
return View();
}
}
}
Create a view corresponding to "Index_submit()" action method which contains a form with a textbox and also contains functionality for posting this form on pressing "Enter" key.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index_submit</title>
</head>
<body>
@using (Html.BeginForm("Index_submit", "Home", FormMethod.Post, new { DefaultButton = "submit_btn", id = "Formbeg" }))
{
<span>Name:</span>@Html.TextBox("name")<br />
<span>Please Enter value and then press Enter Key</span><br />
<input type="submit" name="btnSubmit" id="submit_btn" value="Submit" />
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Formbeg").keypress(function (e) {
keycode = e.keyCode || e.charCode || e.which //for cross browser
if (keycode == 13) //keyCode for enter key
{
var defaultbutton = $(this).attr("DefaultButton");
$("#" + defaultbutton).click();
return false;
}
});
});
</script>
</body>
</html>
In above code a "DefaultButton" htmlattribute whose value is button with an id "submit_btn" is set for the form. Whenever any key is pressed keypress event for form is executed there assignment of keycode or charCode or which property of event to a variable keycode. The value of this keycode variable is checked which if 13 i.e keycode for "Enter" key then "DefaultButton" htmlattribute value which is "submit_btn" is assigned to a variable defaultbutton then click event on button with id "submit_btn"(submit button) is fired which ultimately post the form.
Form filled with data :-
Form after pressing "Enter" key :-
0 Comment(s)