Browse Articles

Intermediate

Setting default submit button in MVC3 razor using jQuery

18 Aug 2022
Intermediate
3.26K Views

In Asp.net MVC, sometimes we required to post the form on Enter key press. Asp.net MVC has no default button property like Asp.net. However, we can achieve this functionality by using jQuery in MVC.

Set Form DefaultButton Property using jQuery

 <script type="text/javascript"> $(document).ready(function (){ $("#MyForm").keypress(function (e) { kCode = e.keyCode || e.charCode //for cross browser
 if (kCode == 13) { var defaultbtn = $(this).attr("DefaultButton");
 $("#" + defaultbtn).click();
 return false;
 }
 });
});
</script>
 @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { DefaultButton = "SubmitButton", id = "MyForm" }))
{
 @Html.TextBox("txtname")
 <span>Please Enter value and then press Enter Key</span><br />
 <input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />
} 
Summary

In this article I try to explain the default submit behavior of form in MVC. I hope you will refer this article for your need. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Learn to Crack Your Technical Interview

Accept cookies & close this