skip to Main Content

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


  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) {...}
             });
    });
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search