Minimalism
Minimalism

Reputation: 109

Unable to serialize asp dot net core form using ajax request

I am working on an asp.net core application. I have a form for which I want to make a post request using ajax. The form I am working with is quite large. I don't want to do something like this

var email = $("input[name='email']"); because is really large.

The controller is not receiving any value that the user inputs. It was only null.

I doing like this:

 $("#submit").click(function () {

        $.ajax({
            type: "post",
            url: "/Employee/Create",
            dataType: 'json',
            contentType: false,
            processData: false,
            data:  $("#form1").serialize(),

            success: function (response) {
                console.log(response.length);
              
               
            }
        });
});

#form1 is Id the of the form.

Is there any other method that I can use instead of serialize()? Or I'll have to do var email = $("input[name='email']"); this. Or my code is not in the correct format?

Please help.

Upvotes: 0

Views: 1280

Answers (2)

Rena
Rena

Reputation: 36595

That is because contentType:false tell jQuery to not set any content type header,you need remove it.Then it will set default contentType "application/x-www-form-urlencoded; charset=UTF-8".

$("#submit").click(function () {

    $.ajax({
        type: "post",
        url: "/Employee/Create",
        dataType: 'json',
        //contentType: false,    //remove this...
        processData: false,
        data: $("#form1").serialize(),
        success: function (response) {
            alert("success");
            console.log(response.length);
        }
    });
});

Be sure your backend code like below:

[HttpPost]
//[ValidateAntiForgeryToken]   //be sure do not have this attribute
public JsonResult Create(Employee employee)
{
    //do your stuff...
    return Json(employee);
}

Result: enter image description here

Upvotes: 1

Alper Tunga
Alper Tunga

Reputation: 1

You can also serialize the form as follows.

$("#submit").click(function () {
    const dataToSend = new FormData(form.get(0));
             $.ajax({
                    url: actionUrl,
                    type: 'POST',
                    url: "/Employee/Create",
                    dataType: 'json',
                    data: dataToSend,
                    processData: false,
                    contentType:false,
                    success: function(response) {...}
         });
});

Upvotes: 0

Related Questions