b_900
b_900

Reputation: 149

Access form data in C# controller from AJAX post

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;

}

Upvotes: 3

Views: 3267

Answers (2)

vithal wadje
vithal wadje

Reputation: 197

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.

Upvotes: 2

Willy David Jr
Willy David Jr

Reputation: 9131

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
    }
})

Upvotes: 3

Related Questions