【问题标题】:How to submit a form to an ASP.Net Core API Controller如何向 ASP.Net Core API 控制器提交表单
【发布时间】:2017-10-09 10:33:02
【问题描述】:

我正在使用 ASP.Net Core 2.0 和 C# 开发一个 Angular 2 应用程序。

我是 Angular 2 的新手,我一直在阅读 Angular - Forms 文档并进行搜索,但我还没有找到如何将表单发送到 ASP.Net Api。

现在,我的问题是如何获取表单数据并使用http.post 发送。

Html代码:

<h1>L&iacute;neas</h1>

<p>This component demonstrates fetching data from the server.</p>

<p *ngIf="!lines"><em>Loading...</em></p>
<form (ngSubmit)="onSubmit()" #lineForm="ngForm">
    <table class='table' *ngIf="lines">
        <thead>
            <tr>
                <th>Line Id</th>
                <th>Name</th>
                <th>Line Reference Id</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let line of lines">
                <td>{{ line.lineId }}</td>
                <td><input [(ngModel)]="line.name" placeholder="name" required name="name-{{line.lineId}}"></td>
                <td><input [(ngModel)]="line.lineReferenceId" placeholder="lineReferenceId" name="lineReferenceId-{{line.lineId}}" required></td>
            </tr>
        </tbody>
    </table>

    <button type="submit" class="btn btn-success">Submit</button>
</form>

TypeScript代码:

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'line',
    templateUrl: './line.component.html'
})
export class LineComponent {
    public lines: Line[];
    private baseUrl: string;
    private http: Http;

    constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
        this.http = http;
        this.baseUrl = baseUrl;

        http.get(baseUrl + 'api/Line').subscribe(result => {
            this.lines = result.json() as Line[];
        }, error => console.error(error));
    }

    onsubmit() {
        this.http.post(this.baseUrl + 'api/Line/Save', JSON.stringify(this.data))
            .subscribe(result => { }, error => console.error(error));
    }
}

interface Line {
    lineId: number;
    name: string;
    lineReferenceId: string;
}

我的问题在这里:this.http.post(this.baseUrl + 'api/Line/Save', JSON.stringify(this.data))。我不知道如何获取表单数据:this.data 不存在。

如何获取表格?

顺便说一句,我不知道这是否是在构造函数中获取base url和http客户端的正确方法:

this.http = http;
this.baseUrl = baseUrl;

【问题讨论】:

    标签: javascript forms angular


    【解决方案1】:

    您的数据绑定到变量“行”。所以尝试以下方法:

    onsubmit() {
        this.http.post(this.baseUrl + 'api/Line/Save', JSON.stringify({ lines: lines }))
            .subscribe(result => { }, error => console.error(error));
    }
    

    然后在您的后端找到发布键“行”。 您获取 http 类和 url 字符串的代码很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      相关资源
      最近更新 更多