Reputation: 279
I hope someone could point me in the right direction regarding Ajax post. I have a long form which has a number of questions which are toggled depending on the previous value that was selected.
When I post the form using Ajax, the form submit successfully and the _Success
Partial displays correctly. However, if I make an error in the form and then submit. On post back all JQuery stops working the MVC @Html.ValidationMessageFor
display correctly but the toggled fields are reset along with the green validation.
How do I keep the previous state? Or am I doing this wrong and there a better way to do this?
Thanks in advance!
My code example:
View
<div id="test-container">
@Html.Partial("_PartialView",Model)
</div>
Partial View
<form method="post" action="@Url.Action("SendReport","Report")" data-form-ajax="true" data-form-target="#test-container">
// form fields here
Controller
if (Request.IsAjaxRequest())
{
if (!ModelState.IsValid)
{
// set model
return PartialView("_PartialView",model);
}
// more model methods
if (model.RecordMessage.Type == MessageType.Success)
{
return PartialView("_Success", model);
}
else
{
return PartialView("_PartialView", model);
}
}
Ajax
var ajaxSubmitForm = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
$("#test-container").html("");
$("#test-container").append(data);
});
return false;
};
$("form[data-form-ajax='true']").submit(ajaxSubmitForm);
Upvotes: 0
Views: 764
Reputation: 2469
To re-enable validation you can append back the form to the jquery validator. This should be handled after the append itself.
var form = $("#myForm");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
Also it might be required to reactivate those toggles if you are using some jquery plugin with them.
Upvotes: 1