2017-10-09 6 views
0

私はASP.Net Core 2.0とC#でAngular 2アプリケーションを開発しています。ASP.NetコアAPIコントローラにフォームを提出するには

私は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は存在しません。

フォームはどのように入手できますか?これはコンストラクタでベースURLとHTTPクライアントを取得するための正しい方法であればところで

は、私は知らない。

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

答えて

1

あなたのデータは変数「ライン」にバインドされています。したがって、以下を試してください:

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

次に、バックエンドでポストキー 'lines'を見つけてください。 httpクラスとURL文字列を取得するコードは問題ありません。

関連する問題