从前端传递一个字符串变量(HTML / .ts到C#控制器)。
我浏览了angular.io文档和非官方人员的演练。我观看了视频,但似乎与我的代码无关。我在Visual Studio 2019中启动了一个新项目(带有Angular的ASP.NET Core Web应用程序)。有.ts组件和.cs控制器。我的HTML设置为接受字符串输入。我尝试使用HTTP POST请求和Ajax请求。我可能用错误的论点错误地完成了它们。我咨询过
AngularJS和asp.net MVC-将数据传递给控制器?
还有无数其他不在StackOverflow上的东西。
.html
<input #box (keyup)="onKey(box.value)">
Your name is: {{name}}
.ts
onKey(value: string)
{
this.name = value;
}
我希望该名称字符串在控制器中可用,我可以在其中打印出来,以后再在数据库中使用它。
我使用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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句