Matthew Layton
Matthew Layton

Reputation: 42229

WebApi request parameters are null

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.

Upvotes: 0

Views: 182

Answers (2)

Shoaib Shakeel
Shoaib Shakeel

Reputation: 1547

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)
{
    ...
}

Upvotes: 0

IMujagic
IMujagic

Reputation: 1259

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

Upvotes: 3

Related Questions