我的API使用ASP.Net Core 2,前端使用Angular 4.4.2。
我有一个包含8个字符串属性的模型类,但只需要其中一个属性。仅当所有模型属性都具有值时,我的模型才会被绑定。当我发布数据时,我确保发送空字符串而不是null
值,但即使一个属性没有值,我的模型仍为null
。
使用MVC,如果JSON对象和模型中的属性具有不同的名称,则会出现此问题,但如果字符串为空甚至null
则不会。
C#模型类:
public class CustomerModel
{
public long Id { get; set; } // reusing the same model for edit and setting this to 0 when posting a new customer
public string Title { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Mail { get; set; }
public string ContactName { get; set; }
public string ContactSurname { get; set; }
public string ContactPhone { get; set; }
public string ContactMail { get; set; }
}
动作签名:
public async Task<ActionResult> PostCustomer([FromBody] CustomerModel model)
发布帖子的角色TS代码:
postCustomer() {
this.createCustomer();
if (this.edit) {
this.customerService.editCustomer(this.customer).subscribe(() => {
this.dialogRef.close();
},
reject => {
console.log(reject);
});
} else {
this.customerService.postCustomer(this.customer).subscribe(() => {
this.dialogRef.close();
},
reject => {
console.log(reject);
});
}
}
createCustomer() {
const customer = this.customerForm.value; // using reactive forms
this.customer = new Customer(this.edit ? this.customer.id : 0,
customer.title,
customer.address,
customer.phone,
customer.mail,
customer.contactName,
customer.contactSurname,
customer.contactPhone,
customer.contactMail
);
}
电话会议:
postCustomer(customer: Customer) {
return this.httpClient.post(`/Api/Customer/Post`, customer);
}
Request payload
{"id":0,"title":"ssss","address":"","phone":"","mail":"","contactName":"","contactSurname":"","contactPhone":"","contactMail":""}