使用poster发送数据时嵌套模型不绑定

本文关键字:嵌套 模型 绑定 数据 poster 使用 | 更新日期: 2023-09-27 18:27:38

当我尝试使用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; }
}

我的看跌期权方法如下

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 时出现对象引用错误

有解决这个问题的办法吗?

使用poster发送数据时嵌套模型不绑定

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

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