使用邮递员发送数据时嵌套模型不绑定

时间:2015-12-20 07:08:19

标签: c# asp.net asp.net-mvc wcf asp.net-web-api2

当我尝试使用WebAPI2放置数据时,会出现对象引用错误。我的班级结构就像这样

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

我的Put方法如下所示

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

使用邮递员发送JSON数据。我的JSON数据就像这样

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

当我尝试访问student.address.City

时,我收到了对象引用错误

有什么想法解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

javascript对象的格式不正确,需要用点表示法(与访问控制器中属性值的方式相同)

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