【发布时间】:2020-12-08 11:47:24
【问题描述】:
在 HTML 中,当您单击下面的 exportok() 按钮时,我希望将当前年份(aka.2020)从选定的下拉列表发送到名为 EXPORT 的 .NET MVC 控制器函数HTTPGET 调用"/api/stations/export”.
Admin.component.ts
exportyears = [
{name: '1 July 2019 to 30 June 2020', id: '2019-2020'},
{name: '1 July 2020 to 30 June 2021', id: '2020-2021'},
];
Admin.component.html
<form>
<select formControlName="exportyear" [(ngModel)]="reportyear"(change)="onClickMe()">
<option
*ngFor="let exportyear of exportyears" [ngValue]="exportyears"
>
{{ exportyear.id }}
</option>
</select>
</form>
<button class="btn btn-primary" type="button" (click)="exportOk(exportyears[0].id)">
<i class="glyphicon glyphicon-ok"></i> OK</button>
服务.ts
export(reportyear: string): Observable<Response> {
// let headers = new Headers();
// headers.append('Content-Type', 'application/json');
// headers.append('reportyear', reportyear);
let request = new Request({
method: RequestMethod.Get,
url: environment.baseUrl + "/api/stations/export",
responseType: ResponseContentType.Blob,
body: {reportyear}
}
);
Station.ts
exportOk(reportyear: string) {
this.exporting = true;
this.exportMessage = null;
this.stationsService.export(reportyear)
.subscribe(
(res: Response) => {
this.exporting = false;
this.exportModal.hide();
Utils.launchAttachment(res);
},
error => {
this.exporting = false;
if (error.error) {
this.exportMessage = error.error;
}
else {
this.exportMessage = error;
}
}
);
ASP.NET MVC 控制器 控制器.cs
[HttpGet("export")]
public async Task<IActionResult> Export([FromBody]string reportyear)
{
var obj = reportyear; //show me the year so I can use it further down the line…..
var stations = await stationRepository.GetExportAsync();
......
}
【问题讨论】:
-
你有像 500 或 400 这样的错误吗?如果不是,那么它必须在您发送的内容(url/data)和控制器操作之间。最后你应该有这样的东西:“/api/stations/export/2019-2020”对吗?试试这个 [HttpGet("year")] public async Task
Export(string year) { ... } -
HttpGet括号中的内容必须与函数参数中的相同。尝试使用大括号:[HttpGet("{year}")]。
-
谢谢思南。我得到的错误是:5000/api/stations/export:1 加载资源失败:服务器响应状态为 415(不支持的媒体类型)。将尝试 [HttpGet("export {year}")]。我认为这是因为它无法识别标题。
-
好的,现在我更新到 [HttpGet("export{reportyear}")] 并得到 404 Not Found。
-
在您的 url -> localhost:5000/api/stations/export,站是您的控制器名称,导出是操作。所以你的函数名必须是Export,直到这里一切都好。它不是 [HttpGet("export {year}")] 而是 [HttpGet("{year}")]。
标签: angular asp.net-mvc