如何将数据从组件传递到控制器?

时间:2019-06-25 04:03:25

标签: c# angular typescript asp.net-core

从前端(HTML / .ts到C#控制器)传递一个字符串变量。

我正在浏览angular.io文档以及非官方人员的演练。我观看了视频,但似乎与我的代码无关。我在Visual Studio 2019中启动了一个新项目(带有Angular的ASP.NET Core Web应用程序)。有.ts组件和.cs控制器。我的HTML设置为接受字符串输入。我尝试使用HTTP POST请求和Ajax请求。我可能用错误的论点错误地完成了它们。我已经咨询过

How to send data to an ASP.NET Controller with Angular2

ASP.Net MVC How to pass data from view to controller

Passing Model data from View to Controller and using its values

AngularJS & asp.net MVC - passing data to controller?

还有无数其他不在StackOverflow上的东西。

.html

<input #box (keyup)="onKey(box.value)">
Your name is: {{name}}

.ts

onKey(value: string)
{
    this.name = value;
}

我希望名称字符串在控制器中可用,我可以在其中打印出来,以后再在数据库中使用它。

2 个答案:

答案 0 :(得分:1)

我使用asp.net核心Angular模板创建一个演示,它在Keyup上传递数据。

1.home.component.html

<input #box (keyup)="onKey(box.value)">
Your name is: {{name}}

2.home.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
})
export class HomeComponent {
  name: string;

  constructor(
    private http: HttpClient
  ) { }

  onKey(value: string):void {
    this.name = value;
    const formData: FormData = new FormData();
    formData.append('name', this.name);
    this.http.post('https://localhost:44336/api/SampleData/TestName', formData).subscribe(result => {
      console.log(result);
    }, error => console.error(error));
  }
}

3.SampleData控制器(/ api / sampleData)

[HttpPost("TestName")]
public JsonResult TestName(string name)
    {
        //your logic
        return Json(name);
    }

答案 1 :(得分:0)

按照官方指南:https://angular.io/guide/user-input

<input (keyup)="onKey($event)">
onKey(event: any) { 
    console.log(event.target.value); 
    let inputValue = event.target.value;    
  }

现在inputValue将在“键入事件”中的“输入字段”中存储您的值。