Angular 5 HttpClient Post List to Web Api - 始终为空? [英] Angular 5 HttpClient Post List to Web Api - always null?

查看:25
本文介绍了Angular 5 HttpClient Post List to Web Api - 始终为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置是 Angular 5 和 .net core Web Api.在控制器上,模型绑定在尝试绑定到复杂对象时总是导致 null.

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.

代码如下.

此示例改编自另一个 SO 答案.但它不适合我.

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

控制器:

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

型号:

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

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

客户端:

    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);
    }

}

推荐答案

修改 DemoPostViewModel 以包含如下构造函数:

Modify DemoPostViewModel to include a constructor like below:

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

这篇关于Angular 5 HttpClient Post List to Web Api - 始终为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆