【发布时间】:2019-04-13 23:53:33
【问题描述】:
我正在尝试以 xml 格式将数据从 Angular 应用程序发送到“添加”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; }
}
【问题讨论】:
标签: angular asp.net-web-api asp.net-web-api2 angular6 xml-serialization