Im trying to send JSON data to the Api controller where HttpPost can add that data to file.
JSON File:
{
"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: public class Student { public int Id { get; set; } public string Name { get; set; }
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);
}
});
I want send data from view to my api controller so that api can add that data to my file.
my api is working fine but there is some issue with ajax because it is not sending data to my api.

