Prevent default behavior of submit in Ajax.BeginForm with .on() method of jQuery
-
28-06-2021 - |
سؤال
I have a form in my view where I use Ajax.BeginForm
. I want to change the default behavior of the submit button with Javascript code. I've attached a handler with .on()
method and inside the handler, I called the preventDefault()
method. I'm wondering to know why when I attach the handler to the root DOM element, the default behavior is not cancelled but when I attach the handler directly to the form DOM element, the default behavior is cancelled.
The view:
@using (this.Ajax.BeginForm("GetList", "Report", null, new AjaxOptions(), new {id = "OptionForm"}))
{
<input type="submit" id="submitButton"/>
}
The script to attach handler to the root DOM element (Doesn't work):
<script type="text/javascript">
$(function () {
$(document).on("submit", "#OptionForm", refreshGrid);
})
</script>
The handler:
refreshGrid: function (event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data.success) {
$("#ReferenceList").html(data.result);
}
else {
$("#ValidationSummary").html(data.result);
}
}
});
}
And finally the code to attach the handler to the form DOM element (Works):
<script type="text/javascript">
$(function () {
$("#OptionForm").submit = refreshGrid;
})
</script>
المحلول
There's really no point of using an Ajax.BeginForm
if you are going to handle the AJAX submission manually. A standard Html.BeginForm
would suffice, because you don't need to cumulate multiple .submit()
handlers:
@using (Html.BeginForm("GetList", "Report", null, FormMethod.Post, new { id = "OptionForm" }))
{
<input type="submit" id="submitButton" />
}
and then:
<script type="text/javascript">
$(function () {
$(document).on('submit', '#OptionForm', refreshGrid);
});
</script>
and the refreshGrid
function:
var refreshGrid = function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
if (data.success) {
$('#ReferenceList').html(data.result);
}
else {
$('#ValidationSummary').html(data.result);
}
}
});
return false;
}