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.
3
Answers
I am not sure what is your HTML structure, but you may just try this to check if your AJAX post call is sending data correctly.
Initialize JSON data variable like this:
Call make AJAX call:
you don’t have to use ‘JSON.stringify’ in data variable, update your url like this:
also this code provides a cleaner and more accurate method for json data:
https://stackoverflow.com/a/73632045/12645793
Problem is you stringify the nested students array. As you already defined that you accepts the
Students
class as parameter of theAction
. And inside thatStudents
class you mentionList<Student>
Resolution:
stringify
the main object not the nested objects.Replace
With
Ajax Call (Text Data)
Action Method