Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get FormData object and submit the form data by ajax use asp.net mvc

I would like to get a form object and submit the data to server with a button click in Asp.net MVC.

This is my HTML code:

<form method="post" form-sync="ajax">
  @Html.Hidden("InvtId", item.InvtId)
</form>

This is my JS code:

$(document).on("click", "[form-sync='ajax']", function() {
  var formdata = new FormData($(this).closest("form")),
    url = $(this).data("url");
  $.ajax({
    url: url,
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false,
    success: function(response) {
      alert(response.message);
      return false;
    },
  });
});

This is my MVC code:

var data = Request["InvtId"];

The problem is the data variable is empty

Any help would be greatly appreciated, thanks.

like image 792
denli8 Avatar asked Jun 02 '26 04:06

denli8


2 Answers

  • Your form-sync attribute is non standard so your HTML is invalid. You should make that a data attribute.
  • You need to hook to the submit event of the form, not click.
  • The FormData constructor expects a DOMElement, not a jQuery object as you are currently passing to it. You can just give the this reference as that is the DOMElement.
  • The form has no data-url attribute. I assume you want the action property instead, which will default to the current page as you haven't provided one explicitly.
  • The return statement in your success handler is redundant.
  • You need to stop the standard form submission (as you're submitting via AJAX instead) by calling preventDefault() on the passed submit event.

Here's a complete example with all the above fixes:

<form method="post" data-form-sync="ajax">
    @Html.Hidden("InvtId", item.InvtId)
</form>
$(document).on('submit', '[data-form-sync="ajax"]', function(e) {
    e.preventDefault();
    $.ajax({
        url: this.action,
        type: 'post',
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (result) {
            alert(result.message);
        },
    });
})
like image 90
Rory McCrossan Avatar answered Jun 03 '26 17:06

Rory McCrossan


The problem is that you are passing in a jQuery element and NOT a DOM element.
For the FormData to actually return what you expect, you need to pass in a DOM element to its constructor.

Here, try this instead:

var formdata = new FormData($(this).closest("form")[0]);

Another problem is that the form has no data-url attribute.
Use the action property instead, it will return the url of the current page if you have not given a url yourself.

Here, use this instead:

var url = this.action; // or $(this).prop('action');

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!