0

I am making simple ajax post call like

$(document).on("submit", function () {
        var formdata = new FormData($('form').get(0));
        $.ajax({
            url: '@Url.Action("addCustomerTesting", "Auto")',
            type: 'POST',
            data: formdata,
            success: function (result) {
                alert("test");
                if (result != false) {
                    alert("test");
                }
            },
            error: function () {
                alert("test");
                $(".loading-ajax").hide();
            }
        });
    });

In response I get an .json file, ajax success method not receiving the response result. I have the action is as follows

        [HttpPost]
        public ActionResult addCustomerTesting(AddCustomerVM model, HttpPostedFileBase[] CustomerDocuments)
        {
            return Json(new { result = 0, message = "Success" }, JsonRequestBehavior.AllowGet);
        }

the response is shown in a blank page as .json file as enter image description here

Community
  • 1
  • 1
Nomi Ali
  • 2,165
  • 3
  • 27
  • 48
  • Try using `preventDefault()` to stop the form being submitted. – DavidG Mar 22 '16 at 11:03
  • Your making an ajax call and a normal submit (you have not cancelled the default submit). but your ajax call does not work because you have the incorrect options. Refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Mar 22 '16 at 11:04
  • @StephenMuecke you saved my time. Thanks a lot – Nomi Ali Mar 22 '16 at 11:08
  • If you want a simple ajax call, you don't need to do it on a submit action, you can use a simple button as fire your ajax call on a click event. – Ricardo Pontual Mar 22 '16 at 11:09
  • @RicardoPontual in that case I was not able to populate all the form values in formdata parameter passing in data. – Nomi Ali Mar 22 '16 at 11:10
  • @NomiAli, You can use a normal button, but handling the `.submit()` event is generally better because its also triggering any jquery validation. You just need to make sure you cancel the default action. –  Mar 22 '16 at 11:17
  • @StephenMuecke can I validate fields that are having data annotation attribute define in view model in same jquery submit method? – Nomi Ali Mar 22 '16 at 12:09
  • Yes if you use a submit button and `$('form').submit(function() { ...` then validation will be run, but if you use a normal button you call it manually (and cancel the ajax call if its not valid) –  Mar 22 '16 at 12:13
  • It doesn't show error messages by default, am I need to write script to validate element one by one and than show in a summary? – Nomi Ali Mar 22 '16 at 12:16

0 Answers0