Ich habe einen Controller, der eine Create
Aktion hat. Sein Zweck ist es, einen Namen und Daten aus dem Dateiformat zu erhalten, und IndexViewModel
geben IEnumerable<File>
Dateien zurück.So senden Sie Daten an einen ASP.NET-Controller mit Angular2
public class HomeController : Controller
{
static List<Models.File> files = new List<Models.File>();
public HomeController() { }
[HttpGet]
public IActionResult Index() => View(new IndexViewModel { Files = files });
[HttpGet]
public IActionResult Create() => View();
[HttpPost]
public IActionResult Create(IFormFile file)
{
var filename =
ContentDispositionHeaderValue.Parse(file.ContentDisposition)
.FileName;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var content = reader.ReadToEnd();
files.Add(new Models.File { Name = filename, Data = content });
}
return RedirectToAction(nameof(Index));
}
}
Wenn ich ein Formular in statischen html verwenden, es ist in Ordnung, der Server die Daten empfängt. Aber wenn ich das gleiche Formular in einer Angular2 Vorlage verwende, tut es das nicht.
import {Component} from 'angular2/core';
import {File} from './file';
@Component({
selector: 'listfile',
template: `
<form method="post" asp-action="Index" asp-controller="Api/File" enctype="multipart/form-data">
<input type="file" name="files" #newFile (keyup.enter)="addFile(newFile.value)"
(blur)="addFile(newFile.value); newFile.value='' ">
<input type="submit" value="Upload" />
</form>
<table class="table">
<th>id</th><th>name</th>
<tr *ngFor="#file of files">
<td>{{file.id}}</td>
<td>{{file.name}}</td>
</tr>
</table>
`
})
export class ListFileComponent {
files = [
new File(1, 'file1'),
new File(2, 'file2')
];
addFile(newFile: string) {
if (newFile) {
this.files.push(new File(this.files.length + 1, newFile.split(/(\\|\/)/g).pop()))
}
}
falert(value) {
alert(value);
}
}
Vielen Dank für die Antwort, habe es, tolle Post! Ich denke, die zweite Option ist schöner. –