[英]Not able to Send Data from view to Api controller
我试图将 JSON 数据发送到 Api controller ,其中 HttpPost 可以将该数据添加到文件中。
JSON 文件:
{
"students":
[
{
"Id": 1,
"Name": "Ravi",
"Department": "IT"
},
{
"Id": 2,
"Name": "Raj",
"Department": "hr"
},
{
"Id": 3,
"Name": "avi",
"Department": "it"
},
{
"Id": 0,
"Name": "string",
"Department": "string"
},
{
"Id": 8,
"Name": "tanmay",
"Department": "SDE"
},
{
"Id": 10,
"Name": "test",
"Department": "Dev"
},
{
"Id": 78,
"Name": "abhi",
"Department": "IT"
},
{
"Id": 42,
"Name": "grgr",
"Department": "grgsrgs"
},
{
"Id": 32,
"Name": "wer",
"Department": "new"
},
{
"Id": 450,
"Name": "tan",
"Department": "ted"
}
]}
CLass:公共 class 学生 { 公共 int Id { 获取; 放; } 公共字符串名称 { 获取; 放; }
public string Department { get; set; }
}
public class Students
{
public List<Student> students { get; set; }
}
API controller
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
public List<Student> students { get; set; }
[HttpPost]
public IActionResult AddUser(Students _Student)
{
var filePath = @"C:/Users/tanmay_pawar/source/repos/CRUDAPI/CRUDAPI/output.json";
var json = System.IO.File.ReadAllText(filePath);
Students students = JsonConvert.DeserializeObject<Students>(json);
students.students.AddRange(_Student.students);
json = JsonConvert.SerializeObject(students);
System.IO.File.WriteAllText(filePath, json);
return Ok();
}
}
jQuery:
oStudent =
{
"students": [
{
Id: $("#st-Id").val(),
Name: $("#st-Name").val(),
Department: $("#st-Department").val()
}
]
}
var postApiUrl = "https://localhost:7018/api/Students"
$.ajax({
url: postApiUrl,
type: 'POST',
data: JSON.stringify(oStudent.students),
contentType: 'application/json',
dataType: 'json',
success: function (msg) {
alert(msg);
}
});
我想将数据从视图发送到我的 api controller 以便 api 可以将该数据添加到我的文件中。
我的 api 工作正常,但 ajax 存在一些问题,因为它没有向我的 api 发送数据。
我不确定你的 HTML 结构是什么,但你可以试试这个来检查你的 AJAX 后调用是否正确发送数据。
像这样初始化 JSON 数据变量:
var data = [{ "Id": "1", "Name": "Student name 1","Department":"Dept 1"},
{ "Id": "2", "Name": "Student name 2","Department":"Dept 2"}
];
拨打 AJAX 电话:
var postApiUrl = "/api/Students";
$.ajax({
url: postApiUrl,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
dataType: 'json',
success: function (msg) {
alert(msg);
}
});
在您的 javascript 中,您还缺少“;” 提供 URL 的行上的分号。
帖子 api URL 中缺少操作名称。
您不必在数据变量中使用“JSON.stringify”,像这样更新您的 url:
var postApiUrl = "https://localhost:7018/api/Students/AddUser";
$.ajax({
url: postApiUrl,
type: 'POST',
data: {
Id: $("#st-Id").val(),
Name: $("#st-Name").val(),
Department: $("#st-Department").val()
},
contentType: 'application/json',
dataType: 'json',
success: function (msg) {
alert(msg);
}
});
此代码还为 json 数据提供了一种更清洁、更准确的方法: https://stackoverflow.com/a/73632045/12645793
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.