【问题标题】:How to pass data from component to controller?如何将数据从组件传递到控制器?
【发布时间】:2019-06-25 04:03:25
【问题描述】:

从前端(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;
}

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

【问题讨论】:

  • 你能提供更多关于你拥有什么的细节吗?提供Minimal, Reproducible Example?例如,您如何将其发送到 asp.net core(您的服务)和您的 asp.net api 控制器。

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


【解决方案1】:

我使用 asp.net core 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);
    }

【讨论】:

  • 这正是我想要的。谢谢!
【解决方案2】:

根据官方指南:https://angular.io/guide/user-input

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

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

【讨论】:

  • 抱歉,这不是问题的答案。在你的辩护中,你不能真正回答这个问题,因为它有点不连贯。还是等到改进后再回答比较好
  • 我为我快速整理的问题道歉。但是如你所见,我的 .ts 和 .html 文件已经有了这个功能。
猜你喜欢
  • 2020-06-11
  • 2018-10-07
  • 2017-03-05
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 2011-10-03
  • 1970-01-01
相关资源
最近更新 更多