skip to Main Content

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


  1. 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:

    var data = [{ "Id": "1", "Name": "Student name 1","Department":"Dept 1"},
                  { "Id": "2", "Name": "Student name 2","Department":"Dept 2"}
    ];
    

    Call make AJAX call:

    var postApiUrl = "/api/Students";
    
    $.ajax({
        url: postApiUrl,
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType: 'json',
        success: function (msg) {
        alert(msg);
    }
     });
    

    In your javascript you are also missing ";" semi-colon on the line
    where you are providng URL.

    Login or Signup to reply.
  2. you don’t have to use ‘JSON.stringify’ in data variable, update your url like this:

    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);
    }
     });
    

    also this code provides a cleaner and more accurate method for json data:
    https://stackoverflow.com/a/73632045/12645793

    Login or Signup to reply.
  3. Problem is you stringify the nested students array. As you already defined that you accepts the Students class as parameter of the Action. And inside that Students class you mention List<Student>

    Resolution: stringify the main object not the nested objects.

    Replace

    data: JSON.stringify(oStudent.students)
    

    With

    data: JSON.stringify(oStudent)
    

    Ajax Call (Text Data)

    Ajax Call

    Action Method

    Action Method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search