Setting a Default Button in ASP.NET MVC using jQuery

In ASP.NET MVC, there's no concept of a default button as there is in ASP.NET WebForms. To mimic this functionality, this can be accomplished quite painlessly using jQuery. Here's the code to do it.

<script type="text/javascript">
ButtonKeys = { "EnterKey": 13 };
$(function() {
$("#MainForm").keypress(function(e) {
if (e.which == ButtonKeys.EnterKey) {
var defaultButtonId = $(this).attr("defaultbutton");
$("#" + defaultButtonId).click();
return false;
<% using (Html.BeginForm("DefaultButtonTest", "Home", FormMethod.Post,
new { defaultbutton = "SubmitButton",id="MainForm" })){%>
<%= Html.TextBox("test")%>
<input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />

If you run this example and view the HTML source, you'll see the defaultbutton attribute has been added

<form action="/Home/DefaultButtonTest" defaultbutton="SubmitButton"
id="MainForm" method="post">
input id="test" name="test" type="text" value="" />
input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />
input type="submit" name="btnSubmit" id="CancelButton" value="Cancel" />

Will you give this article a +1 ? Thanks in advance

About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at Follow him on twitter @malcolmsheridan


0 Responses to "Setting a Default Button in ASP.NET MVC using jQuery"

Copyright © 2009-2015 All Rights Reserved for by Suprotim Agarwal | Terms and Conditions