I have a parent form that is using a modal form to update it. Once the user is finished with the modal form:
- I want it to close the modal form
- Trigger a post-back which will call a controller function to update a database table
- Avoid redirecting using the default submit action (
e.preventDefault()
)
My problem is that if I remove the default submit event, no post-back occurs and my database table stays unmodified. I am using AJAX to modified the text on the parent form to reflect the user updates.
How can I force a post back without leaving the parent form? I do not want to reload the webpage; only update values, close the modal form and trigger a post event to call an update function.
NOTE: If I omit the preventDefault()
event, the webpage always redirects to the url: /client/UpdateClientDetails/' + id
Please see below for my code snippets:
AJAX snippet
<script type="text/javascript">
$('.btn-primary').click(function (e) {
$.ajax({
url: '/Client/UpdateClientDetails',
type: 'POST',
dataType: 'json',
data: newClient = {
address1: $("#clientAddress1-@Model.Id").val(),
address2: $("#clientAddress2-@Model.Id").val(),
city: $("#clientCity-@Model.Id").val(),
province: $("#clientProvince-@Model.Id").val(),
postalCode: $("#clientPostalCode-@Model.Id").val(),
phoneNumber: $("#clientPhoneNumber-@Model.Id").val()
},
cache: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Address1-@Model.Id").text(newClient.address1);
$("#Address2-@Model.Id").text(newClient.address2);
$("#City-@Model.Id").text(newClient.city);
$("#Province-@Model.Id").text(newClient.province);
$("#PostalCode-@Model.Id").text(newClient.postalCode);
$("#PhoneNumber-@Model.Id").text(newClient.phoneNumber);
$("#dialog-actions").dialog('close');
},
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
});
Beginning of modal form
@using (Html.BeginForm("UpdateClientDetails", "Client", FormMethod.Post, attributes))
{
//HTML Helpers & other things here
}
Controller method I want to invoke
[HttpPost]
public void UpdateClientDetails(Client newClientDetails)
{
_clientService.UpdateClient(newClientDetails);
}