Thursday, 7 July 2016

MVC Submit form using AJAX

In MVC often we need to write some code after submit the form to display notifications. For this solution I have created a js function that capture the submit button's click and post the form asynchronously. For more info check this out.


Step 1: Create "wireUpSubmitForm" function in your js file like below. This wireUpSubmitForm accepts 3 parameters. First parameter is id of form. Second parameter is success callback function that will execute on success of post request. 3rd parameter is error callback function that will execute on any server error while making a post request to the server. In this method I am fetching the request url with id of form like '$(formId).attr('action')'.

function wireUpSubmitForm(formId, successCallback, errorCallBack) {
    $(formId).submit(function (event) {
        event.preventDefault();
        if ($(formId).valid()) {
            $.ajax({
                type: "POST",
                url: $(formId).attr('action'),
                data: $(formId).serialize(),
                success: function (response) {
                    successCallback(response);
                },
                error: function (response) {
                    errorCallBack(response);
                }
            });
        }
    })
}

Step 2: Create register form like below. 

<div class="mainWindow">
    <h4>Register</h4>
        @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", id = "formRegister" }))
        {
            <div class="row">
                @Html.Partial("_RegisterPartial")
            </div>
            <div class="row">
                <label class="col-md-2 control-label">&nbsp;</label>
                <div class="col-md-10">
                    <div class="text-left" id="divError"></div>
                    <button type="submit" class="btn btn-success">Submit</button>
                    <a class="btn btn-default" href="/account/login">Cancel</a>
                </div>
            </div>
        }
</div>

Step 3: Now Call that wireUpSubmitForm on document.ready function of jquery. 

<script type="text/javascript">
    $(document).ready(function () {
        wireUpSubmitForm("#formRegister", function (response) {
            //sussess part
        }, function (response) {
            //error part
        });
    });
</script>

No comments:

Post a Comment