-1

Object reference error getting when I'm trying to put data using WebAPI2. My class structure is like this

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Address address { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public int StudentId { get; set; }
    public string City { get; set; }
    public string AddressLine { get; set; }
}

My Put method is like below

public async Task putStudentProfile(Student student)
{
    tblStudent std= db.tblStudent .FirstOrDefault(p => p.ID == student.Id);
    std.NAME = student.Name;
    std.EMAIL= student.Email;
    tblAddress addr= db.tblAddress.FirstOrDefault(q => q.ID == student.Id);
    addr.City= student.address.City;
    await db.SaveChangesAsync();
}

Sending JSON data using postmen. My JSON data is like this

{
"Id":59,
"Name": "Sandeep",
"Email": "xxxxxxxx@xxxx.com",
"address":{
    "Id":42,
    "StudentId": "59",
    "City": "xxxxxx",
    "AddressLine":"xxxxxxxxxxxxx"
    }
}

I'm getting object reference error when I try to access student.address.City

Any idea to solve this?

  • Because the `address` property of `student` is `null` –  Dec 20 '15 at 07:11
  • @StephenMuecke Thanks for your comment, i'm sending data from the postmen. How can i initialized address property of student? any advice? – sandeep nagabhairava Dec 20 '15 at 07:14
  • If your sending the data correctly, then the `DefaultModelBinder` will initialize and bind the `address` property. You need to edit your question showing how you send the data to the controller (and then I will reopen the question) –  Dec 20 '15 at 07:17
  • 1
    Change it to `"address.Id": 42`, `"address.StudentId": "59"` etc (remove the `"address":{ ... }`) –  Dec 20 '15 at 07:38
  • @StephenMuecke Thanks for your support. – sandeep nagabhairava Dec 20 '15 at 07:42

1 Answers1

2

The format of the javascript object is incorrect and needs to be in dot notation (the same way you would access the values of the property in the controller)

{
    "Id":59,
    "Name": "Sandeep",
    "Email": "xxxxxxxx@xxxx.com",
    "address.Id": 42,
    "address.StudentId": 59,
    "address.City": "xxxxxx",
    "address.AddressLine": "xxxxxxxxxxxxx"
}
  • Since it is not really valid JSON representation of object would you mind to add link that explains this behavior? – Alexei Levenkov Dec 20 '15 at 08:03
  • @AlexeiLevenkov, Because the default for postman is `x-www-form-urlencoded`, the `DefaultModelBinder` needs it in this format. Otherwise it would need to be stringified (e.g. `JSON.stringify()` and the `contentType` set to `'json'` - but I'm not familiar enough with postman to know if that can be done (will do a bit of extra research later) –  Dec 20 '15 at 08:11