angular - 如何使用 Angular2 将数据发送到 ASP.NET Controller

标签 angular typescript asp.net-core-1.0

我有一个带有 Create 的 Controller 行动。它的目的是从文件形式接收名称和数据,并且IndexViewModel返回 IEnumerable<File>文件。

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));
    }
}

当我在静态 html 中使用表单时,没问题,服务器接收数据。但是当我在 Angular2 模板中使用相同的表单时,它不会。

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);
    }
}

最佳答案

您对 Angular2 模板和 MVC 预处理有误解。 Here is a post这可能会清除它。您有 ASP.NET 标签助手,它们不会在服务器上呈现,而是按原样发送到客户端。

您正在使用 form post which passes form data ,相反,您应该将 Web APIAngular2 的 Http 一起使用服务。

您有很多选择,但目前最实用的有两个:

  1. 您可以选择使用 MVC 的强大功能进行预处理,并让分部 View 返回表单。在您的组件中,您使用 templateUrl 而不是 template 并指向将预处理标签助手并返回的 /controller/action根据需要生成 HTML(这将用作 Angular2 模板。
  2. 您可以开始利用 Angular2 作为真正的 SPA,并且只使用 MVC 为单个页面提供服务...... /home/index。然后使用 templateUrl 指向用作模板的本地 .html 文件。并构建一个 API 来支持您需要的所有交互。

我希望这能解决问题!


如果您要使用内联或静态 .html,则需要删除 ASP.NET 标记助手。

@Component({
    selector: 'listfile',
    template: `
<form (submit)="" >
    <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 {
    // ...
    constructor(private http: Http) { }
    onSubmit() {
       const body = JSON.stringify({ this.files });
       this.http
           .post('api/file/create', 
                 body, 
                 { headers: new Headers({ "Content-Type": "application/json" }) })
           .map(response => response.json())
           .subscribe(json => { /* handle it */ });
    }
}

然后您必须更改 API 签名才能更准确地接受数据。

关于angular - 如何使用 Angular2 将数据发送到 ASP.NET Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36919159/

相关文章:

angular - 如何创建自定义 Angular Material 模块?

javascript - 如何实现记住我的功能?

.net - 在 ASP.NET Core 中找不到 ClientAssertionCertificate

.net - 创建 .net 类库时出现不受支持的框架错误

css - 如何在angular 6中的prime-ng tabview选项卡中添加样式?

Angular Material Table - 异步数据源的问题

angular - 如何使用 ngrx-entity 更新实体子集?

javascript - TSconfig:为每个ts文件夹编译一个新的js文件夹

typescript - 重叠类型的类型定义

请求线程外部的 ASP.NET Core RC2 SignalR Hub 上下文