1

JSON File:

{
    "Students": [
{
  "id": 1,
  "name": "Ravi",
  "department": "IT"
},

{
  "id": 2,
  "name": "Raj",
  "department": "hr"
},
{
  "id": 3,
  "name": "avi",
  "department": "it"
}
]}

ASP.NET MVC model classes:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
}

public class Root
{
    public List<Student> Students { get; set; }
}

ASP.NET MVC controller for receiving data from a jQuery POST request, and sending that data to the API:

public class StudentController : Controller
{
    HttpClientHandler _clientHandler = new HttpClientHandler();

    [HttpPost]
    public async Task<List<Student>> AddUser(Student _Students)
    {
        OStudents = new List<Student>();

        using (var httpclient = new HttpClient(_clientHandler))
        {
            StringContent content = new StringContent(JsonConvert.SerializeObject(_Students), Encoding.UTF8, "application/json");

            using (var response = await httpclient.PostAsync("https://localhost:7018/api/Students/AddUser", content))
            {
                string res = await response.Content.ReadAsStringAsync();
                OStudents = JsonConvert.DeserializeObject<List<Student>>(res);
            }
        }

        return OStudents;
    }
}

jQuery code: for sending data to AddUser function:

function AddStudent() {
    oStudent = {
    id: $("#st-Id").val(),
    name: $("#st-Name").val(),
    department: $("#st-Department").val()
};

$.post("/Student/AddUser", oStudent);
$.ajax({
    url: "/Student/AddUser",
    type: 'POST',
    data: oStudent,
    contentType: 'application/json',
    dataType: 'json',
    success: function (msg) {
        alert(msg);
    }
});

Web API files:

Classes:

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

ApiController for adding data received from ASP.NET MVC application to JSON file

    [HttpPost("AddUser")]
    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();
    }

My POST method in the Web API is receiving null values.

1 Answer 1

1

oStudent is not a JSON object. It is a normal JavaScript object. If you want to send the data as JSON, you have to encode it first:

data: {_Student: JSON.stringify(oStudent)}

You can receive this data with a string type parameter on the server side and then deserialize the object.

[HttpPost("AddUser")]
public IActionResult AddUser(string _Student)
{
    List<Student> students = JsonConvert.DeserializeObject<List<Student>>(_Student);        

    return Ok();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.