【问题标题】:How to send data to an ASP.NET Controller with Angular2如何使用 Angular2 将数据发送到 ASP.NET 控制器
【发布时间】:2016-12-14 20:11:48
【问题描述】:

我有一个具有Create 操作的控制器。其目的是从文件形式接收名称和数据,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);
    }
}

【问题讨论】:

    标签: angular typescript asp.net-core-1.0


    【解决方案1】:

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

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

    你有很多选择,但其中两个是目前最实用的:

    1. 您可以选择使用 MVC 的强大功能进行预处理,并让部分视图返回表单。在您的组件中,您使用 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 签名以更准确地接受数据。

    【讨论】:

    • 感谢您的回答,明白了,好帖子!我认为第二个选项更好。
    猜你喜欢
    • 2013-09-28
    • 2020-04-09
    • 1970-01-01
    • 2021-03-17
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2016-02-07
    相关资源
    最近更新 更多