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;
}
2
Answers
Use serialize if you will send form values:
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)
The final code would look like this:
The following post will help you
Post Data Using jQuery in ASP.NET MVC
Your code should be
Model class Person.cs
jQuery function to get the form data, I am assuming here you have submit button on your form
Your HomeController method
Form values in the controller
Let me know, if any clarification required.