[英]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.我正在使用 AJAX 向 c# controller 发送表单数据,但是我不知道如何访问 Z5904C10AZ3F2C06E1 中的数据。 I am trying to pass the form data into the controller as a Person object but I am just returning system.Models.Person.我正在尝试将表单数据作为人员 object 传递到 controller 但我只是返回 system.Models.Person。 I am new to C# so any help would be greatly appreciated, thanks a lot.我是 C# 的新手,所以非常感谢任何帮助,非常感谢。
Javascript 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 Model
public class Person
{
public string name { get; set; }
public string age { get; set; }
}
Controller Controller
public string GetFormData(Person formData)
{
string name = formData.name.ToString();
return name;
}
Use serialize if you will send form values:如果您要发送表单值,请使用序列化:
$form = $(this).serialize();
Use FormData if you be sending a file for upload and alike.如果您要发送文件进行上传等,请使用 FormData。
And on your data declaration, set it as is (without declaring it as a literal JS object)在您的数据声明中,将其设置为原样(不将其声明为文字 JS 对象)
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
}
})
The following post will help you下面的帖子可以帮助你
Post Data Using jQuery in ASP.NET MVC 在 ASP.NET MVC 中使用 jQuery 发布数据
Your code should be你的代码应该是
Model class Person.cs 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 jQuery function 获取表单数据,我假设您的表单上有提交按钮
$(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你的 HomeController 方法
[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 controller 中的表格值
Let me know, if any clarification required.如果需要任何澄清,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.