3

I am sending form data to a c# controller using AJAX, however I don't know how to access the data inside the controller. I am trying to pass the form data into the controller as a Person object but I am just returning system.Models.Person. I am new to C# so any help would be greatly appreciated, thanks a lot.

Javascript

$('#myForm').submit(function(e){
    e.preventDefault();
    const formData = new FormData(e.target);
    $.ajax({
        url: '/Home/GetFormData',
        type: 'POST',
        data: {formData: formData},
        success: function(resultData){
            console.log(resultData)
        },
        error: function(){
            //do something else
        }
    })
}

Model

public class Person 
{
    public string name { get; set; }
    public string age { get; set; }
}

Controller

public string GetFormData(Person formData)
{
    string name = formData.name.ToString();

    return name;

}
4
  • Why to post your form via js ajax if you can do it directly in view with Ajax.BeginForm Commented Apr 20, 2021 at 16:53
  • Generally looks ok, so the question is: what exactly is formData after const formData = new FormData(e.target);? Commented Apr 20, 2021 at 16:53
  • Start with something simple, public string GetFormData(string name) and data: {name: "test"} - then public string GetFormData(string name, int age) then (Person formData) Commented Apr 20, 2021 at 16:58
  • formData is an object of key value pairs, with the keys being the name given to the inputs on my form, so I can do console.log(formData.get(‘name’)) and get the user’s name, but for some reason console.log(formData) returns an empty object. So I presume I’m passing an empty object into the controller but I don’t know how I would fix this. Commented Apr 20, 2021 at 17:14

2 Answers 2

3

Use serialize if you will send form values:

$form = $(this).serialize();

Use FormData if you be sending a file for upload and alike.

And on your data declaration, set it as is (without declaring it as a literal JS object)

data: $form

The final code would look like this:

$('#myForm').submit(function(e){
e.preventDefault();
$form = $(this).serialize();
$.ajax({
    url: '/Home/GetFormData',
    type: 'POST',
    data: $form,
    success: function(resultData){
        console.log(resultData)
    },
    error: function(){
        //do something else
    }
})
Sign up to request clarification or add additional context in comments.

Comments

2

The following post will help you

Post Data Using jQuery in ASP.NET MVC

Your code should be

Model class Person.cs

 public class Person
{
    public string name { get; set; }
    public string age { get; set; }
}

jQuery function to get the form data, I am assuming here you have submit button on your form

 $(document).ready(function () {
    $("#btnSave").click(function () { //Your Submit button
        $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/GetFormData", // Controller/View 
                data: { //Passing data
                    name: $("#txtname").val(), //Reading text box values using Jquery 
                    age: $("#txtage").val(),
                }

            });

    });
});

Your HomeController method

 [HttpPost]
    public ActionResult GetFormData(Person obj)
    {
        string name = obj.name;
        string age = obj.age;
        //Once you have data here then you can pass anywhere i.e. database or some other method

        return View();
    }

Form values in the controller

Values in the controller method

Let me know, if any clarification required.

1 Comment

Thanks to both of you for the help! I managed to solve it by creating an object of key value pairs from FormData and using JSON.stringify() to send it with Ajax, then I could access it in the controller.

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.