0

Here are my models

public class Student { public string FirstName { get; set; } public string LastName { get; set; } public List<Course> Courses { get; set; } } public class Course { public string Name { get; set; } public string Details { get; set; } } 

Here is my WebApi method

[HttpPost] public void SetStudentInfo(Student student) { ... } 

Here is my call from JS (This one works)

$.ajax({ async: false, type: "POST", url: "http://localhost:50067/api/Students/SetStudentInfo", data: { FirstName: "John", LastName: "Smith" }, success: function (xhr) { console.log(xhr); }, error: function (e) { console.log(e); } }); 

Here is my call from JS (This one DOES NOT work)

$.ajax({ async: false, type: "POST", url: "http://localhost:50067/api/Students/SetStudentInfo", data: { FirstName: "John", LastName: "Smith", Courses: null }, success: function (xhr) { console.log(xhr); }, error: function (e) { console.log(e); } }); 

When I send up the second request, the entire student on the WebApi method is null; it's something to do with adding in nested objects but I'm not sure why, or how to fix this.

I've tried stringifying the data, but that doesn't work either.

5

2 Answers 2

3

Try with specifying content type for request data as application/json and also you need to serialize your data using JSON.stringify() function.

You can copy the code below:

var requestData = { FirstName: "John", LastName: "Smith", Courses: null }; $.ajax({ type: "POST", url: "http://localhost:50067/api/Students/SetStudentInfo", data: JSON.stringify(requestData), contentType: "application/json", success: function (xhr) { console.log(xhr); }, error: function (e) { console.log(e); } }); 

Also one tip. Your web api controller should not be void. Api controller should always return something, for example IHttpActionResult

[HttpPost] public IHttpActionResult SetStudentInfo(Student student) { //process your data return Ok();// or BadRequest() } 
Sign up to request clarification or add additional context in comments.

Comments

0

You need to specify content-type like

contentType:"application/json" 

Also you need to use JSON.stringify() method to convert your data to JSON format when you send it, You can read more details at https://stackoverflow.com/a/20226220/2931427

OLD Answer

In your action try this:

[HttpPost] public void SetStudentInfo([FromBody] Student student) { ... } 

1 Comment

complex types are read from the request body by default. This will not cause any error but will do nothing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.