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">
var ButtonKeys = { "EnterKey": 13 };
$(function() {
$("#MainForm").keypress(function(e) {
if (e.which == ButtonKeys.EnterKey) {
var defaultButtonId = $(this).attr("defaultbutton");
$("#" + defaultButtonId).click();
return false;
}
});
});
</script>
<% 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" />
</form>
Tweet
No comments:
Post a Comment