Search code examples
javascriptc#jqueryajaxasp.net-mvc

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;

}

Solution

  • 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.