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.
form-sync attribute is non standard so your HTML is invalid. You should make that a data attribute. submit event of the form, not click. 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.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.return statement in your success handler is redundant. 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);
},
});
})
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With