本文介绍了如何使用Angular2将数据发送到ASP.NET控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有Create动作的控制器.其目的是从文件格式接收名称和数据,然后IndexViewModel返回IEnumerable<File>文件.

I have a controller that has a Create action. Its purpose is to receive a name and data from file form, and IndexViewModel return IEnumerable<File> files.

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 模板中使用相同的表单时,却没有.

When I use a form in static html, it's alright, the server receives the data. But when I use the same form in an Angular2 template it doesn't.

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 预处理有误解. 这是一则帖子,可能会解决这一问题.您有 ASP.NET 标签帮助程序,这些帮助程序将不会在服务器上呈现,而是直接发送给客户端.

You have a misconception of the Angular2 templating and the MVC pre-processing. Here is a post that might clear that up. You have ASP.NET tag helpers that will not be rendered on the server, and instead will be sent to the client as is.

您正在使用传递表单数据的表单帖子,相反,您应该将 Web API Angular2的一起使用 Http 服务.

You are using the form post which passes form data, instead you should be using the Web API with Angular2's Http service.

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

You have many options, but two of them are the most practical at this point:

  1. 您可以选择使用 MVC 的功能进行预处理,并使用部分视图返回表单.在您的组件中,您使用templateUrl而不是template并指向/controller/action,这将预处理标签帮助程序并根据需要返回HTML(然后将其用作 Angular2 >模板.
  2. 您可以开始将 Angular2 用作真正的 SPA ,并且仅使用MVC来提供单个页面... /home/index.然后,您使用templateUrl指向用作模板的本地.html文件.并构建一个API,该API将支持您需要的所有交互.
  1. You can choose to use the power of MVC for its pre-processing and have a partial view return the form. In your component you use the templateUrl instead of the template and point to the /controller/action that would pre-process the tag helpers and return the HTML as desired (this would then serve as an Angular2 template.
  2. You can start leveraging Angular2 as a true SPA, and only use MVC to serve a single page ever... /home/index. Then you use the templateUrl to point to local .html files that serve as the template. And build out an API that will support all the interactions you need.

我希望这可以解决所有问题!


如果要使用嵌入式或静态.html,则需要删除 ASP.NET 标记帮助器.

I hope this clears things up!


If you are going to use the inline or the static .html you'll need to remove the ASP.NET tag helpers.

@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签名才能更准确地接受数据.

Then you'd have to change your API signature to more accurately accept the data.

这篇关于如何使用Angular2将数据发送到ASP.NET控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 23:19
查看更多