Angular 5 HttpClient Post List to Web Api - always null?

依然范特西╮ 提交于 2020-01-05 06:44:10

问题


The setup is Angular 5 and .net core Web Api. At the controller, model binding always results in null while trying to bind to a complex object.

Code is provided below.

This example is adapted from another SO answer . but its not working for me.

Controller:

[Route("demopost1")]
[HttpPost]
public async Task < IntResultEntity > DemoPostList1([FromBody]DemoPostViewModel payload)
{
    return await Task.FromResult(new IntResultEntity { Result = 0 });
}

Models:

public class DemoPostModel {
    public string RelationType { get; set; }
    public int Weight { get; set; }
}

public class DemoPostViewModel {
    public IList<DemoPostModel> SubUnits { get; set; }
}

Client side:

    export class DemoPostComponent implements OnInit {
    constructor(private demoPostSvc: DemoPostService,
        private fb: FormBuilder) { }

    demoData: any[]
    demoPostForm: FormGroup

    submitDemoPost1(form: FormGroup) {
        let formModel = form.value;
        const payload = {
            'subUnits': [
                formModel.demoFormArray.map(element => ({
                    'relationType': element.relationType,
                    'weight': element.weight
                }))
            ]
        };

        this.demoPostSvc.demoPost1(payload)
            .subscribe(data => {
                console.log("Post success.");
            }, error => {
                console.log("Post failed.");
            });

    }

    ngOnInit() {
        this.demoData = [
            { 'relationType': 1, 'weight': 2 },
            { 'relationType': 3, 'weight': 4 },
        ];
        this.demoPostForm = this.fb.group({
            demoFormArray: this.populateForm()
        });
    }

    populateForm(): FormArray {
        let formFields: any[] = [];

        this.demoData.forEach(element => {
            formFields.push(this.fb.group({
                'relationType': element.relationType,
                'weight': element.weight
            }));
        });

        return this.fb.array(formFields);
    }

}

回答1:


Modify DemoPostViewModel to include a constructor like below:

public class DemoPostViewModel
{
    public DemoPostViewModel()
    {
        SubUnits = new List<DemoPostModel>();
    }
    public IList<DemoPostModel> SubUnits { get; set; }
}


来源:https://stackoverflow.com/questions/50044214/angular-5-httpclient-post-list-to-web-api-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!