1

I have a parent form that is using a modal form to update it. Once the user is finished with the modal form:

  1. I want it to close the modal form
  2. Trigger a post-back which will call a controller function to update a database table
  3. 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);
}
Sean
  • 507
  • 1
  • 9
  • 27
  • 1
    Don't use a submit button, just `` and handle it's `.click()` event. But your script is not sending anything data to the controller - you need to add `data: $('form').serialize(),` and its not clear what you think all that code in your `success` callback is supposed to be doing. –  Nov 24 '15 at 03:01

1 Answers1

3

The <input type="submit">, when inside a form element, will submit the form when clicked unless you return false or event.preventDefault();

Omitting preventDefault() will always submit the form because your input is a "SUBMIT". e.preventDefault() it's just like returning false, nothing is really invoked in the server.

Use button instead of submit

Since you are already using AJAX you could do something like this.

Update your controller method to return JsonResult.

    [HttpPost]
public JsonResult UpdateClientDetails(Client newClientDetails)
{
    _clientService.UpdateClient(newClientDetails);
    return Json("Success", JsonRequestBehavior.DenyGet);
}

Javascript.

$(".btn-primary").click(function () {
    $.ajax({
                url: 'URL to your json method',
                type: 'POST',
                dataType: 'json',
                data: 'Build your JSON object and set it here',
                cache: false,
                contentType: 'application/json; charset=utf-8',
                success: function (data) {

                    var returnValue;
                    try {
                        returnValue = data;

                        //Do your logic. 
                        $("#dialog-actions").dialog('close');

                    } catch (e) {
                        // error

                        return;
                    }


                },
                error: function () { alert("Something went wrong! Please contact the system admin.") }
            })
});
Moe
  • 1,599
  • 11
  • 16
  • I'm trying to implement your structure but the `error()` function is always hit. Using Firefox's debugger, I get a 500 Internal Server Error. The **request** header is `Content-Type: application/json; charset=utf-8` but the **response** header is `Content-Type: text/html; charset=utf-8`. Would this discrepancy most likely be the cause of the error? – Sean Nov 24 '15 at 14:59
  • Would you share the URL you are using in your JSON call? – Moe Nov 24 '15 at 15:58
  • The URL is: `'Client/UpdateClientDetails'`. – Sean Nov 24 '15 at 16:12
  • 1
    Use this Instead url: '@Url.Action("UpdateClientDetails", "Controller Name")', OR add "/" to your URL '/Client/UpdateClientDetails' – Moe Nov 24 '15 at 16:14
  • Didn't realize I missed a forward slash.. I have updated the OP to show the new AJAX call. Still receiving an error. I am new to JSON so maybe there is something wrong with my understanding of it. – Sean Nov 24 '15 at 16:20
  • 1
    Replace your error call to this error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } This way you can actually see the real error. – Moe Nov 24 '15 at 16:24
  • It shows `500 Internal Server Error`. Not really sure where to start taking a look to try and troubleshoot. OP updated once more. – Sean Nov 24 '15 at 16:34
  • 1
    Check this out buddy.. http://stackoverflow.com/questions/4789613/ajax-500-internal-server-error – Moe Nov 24 '15 at 16:36
  • 1
    Modified the `url` parameter to `/Client/` and this fixed my `500` error. I was mistaking this URL for the modal form instead of the destination URL. In this case I would assume it would be the default webpage. However a message stating that there is a JSON syntax error appears. I'll take it from here. Your help was much appreciated Moe! – Sean Nov 24 '15 at 17:00