What I want to do: submit a form via ajax and return a partial view into an existing div in the page (without navigating away from the current page)
I learned that ajaxSubmit allows form submission without redirection to other pages.
So, I have got a form:
<form id="addForm" method="post" action="_SaveConcession" enctype="multipart/form-data">
The action _SaveConcession
is a controller method:
public ActionResult _SaveConcession(parameters ...)
{
return PartialView("Common/_PopUpSave");
}
which returns a partial view.
The script:
$('#addForm').submit(function (e) {
e.preventDefault();
...
if (formValid) {
$(this).ajaxSubmit({
type: 'POST',
dataType: "html",
complete: function (data) {
$('#div-for-partial').html(data);
$("#addConcessionWindow").data("kendoWindow").close();
}
});
}
});
using ajaxSubmit
, the behaviour isn't the expected: the contents of div-for-partial
are cleaned and show nothing in it. If I use the traditional ajax, the div-for-partial
is filled with the partial view returned in the controller method. Below is the ajax which works as expected.
$.ajax({
type: 'POST',
url: "/MD/_SaveConcession",
data: { 'id': id },
dataType: "html",
complete: function (data) {
$('#div-for-partial').html(data);
}
});
However, this last approach doesn't suit me as the partial view is returned into a new page - that's why I'm trying to use ajaxSubmit.
You can use the MVC approach with the AJAX form helper
@using (Ajax.BeginForm("_SaveConsession", "MD", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "div-for-partial", OnSuccess = "postSuccess", OnFailure = "postFailed" }))
{
// your form fields here
}
<script>
function postSuccess() {
// anything else that needs handled after successful post
}
function postFailed() {
alert("Failed to submit");
}
</script>
The ajaxOptions "InsertionMode" and "UpdateTargetId" work together to tell your view that the data being returned needs to be inserted into the specified target id.