0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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) {...}
         });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.