我正在尝试将数据从角度应用程序以xml格式发送到“添加” webapi方法。 我能够绑定普通属性,但嵌套的Phone对象没有绑定。 请帮助我将Phone对象绑定到webapi模型。
以下是我的代码:-
PatientModel.ts
export class Patient {
PatientId: string;
FirstName: string;
Phone: TelephoneNumber;
}
export class TelephoneNumber {
CellPhone: number;
}
Add-Patient.component.ts
ngOnInit() {
this.addForm = this.formBuilder.group({
PatientId: ['', Validators.required],
FirstName: ['', Validators.required],
Phone: this.formBuilder.group({
CellPhone:['',Validators.pattern("[0-9]\\d{9}")]
})
});
};
this.patientService.addPatient(this.addForm.value)
.subscribe( data => {
this.router.navigate(['patient']);
});
Patient.service.ts
addPatient(patient: Patient) {
const postedData =`<Patient
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<PatientId>${patient.PatientId}</PatientId>
<FirstName>${patient.FirstName}</FirstName>
<Phone>
<CellPhone xsi:nil="true">${patient.Phone.CellPhone}</CellPhone>
</Phone>
</Patient>`
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Content-Type', 'text/xml');
httpHeaders = httpHeaders.append('Accept', 'text/xml');
return this.http.post(this.baseUrl+"/add" ,postedData , { headers:
httpHeaders });
}
add.patient.component.html
<form [formGroup]="addForm" (ngSubmit)="onSubmit()">
<div class="form-group" formGroupName="Phone">
<label for="CellPhone">Cell Phone:</label>
<input formControlName="CellPhone" placeholder="Cell Phone"
class="form-control" [ngClass]="{ 'is-invalid': submitted &&
f['Phone'].controls['CellPhone'].errors }">
<div *ngIf="submitted && f['Phone'].controls['CellPhone'].errors"
class="invalid-feedback">
</div>
</div>
<button class="btn btn-success">Save</button>
</form>
WebApi控制器方法
[HttpPost]
public IHttpActionResult Add(Patient p)
{
int response =this._patientService.AddPatient(p);
if (response == -1)
return Conflict();
else
return Ok("Data posted successfully");
}
患者分类
public class Patient
{
public string PatientId { get; set; }
public string FirstName { get; set; }
public TelephoneNumber Phone { get; set; }
}
public class TelephoneNumber
{
public int? CellPhone { get; set; }
}
答案 0 :(得分:0)
如果所有值都已传递到Web api服务器,请通过Fiddler检查网络请求。 如果一切都通过网络传递,请为您的复杂类型实现模型绑定器
[HttpPost]
public IHttpActionResult Add([ModelBinder(typeof(PatientBinder))]Patient p)
{
}
有关如何实现模型活页夹的信息,请参阅下面的URL
https://www.c-sharpcorner.com/article/parameter-binding-in-asp-net-web-api/