[英]How to pass data from asp.NET MVC to Angular2
将数据从 ASP.NET MVC 控制器传递到 Angular 2.0 组件的最佳方法是什么? 例如,我们使用 ASP.NET MVC 模型并希望将它的 JSON 版本发送到 Angular 以在 Angular 中使用它。
当控制器为视图提供服务时,我们已经可以将一些数据推送到 Angular2(模型)。 因此不需要额外的 AJAX 调用来获取该数据。
但是,我正在努力将它“注入”到 Angular 组件中。 你怎么做? 对此有什么好的参考吗? 您可能已经注意到,我对 Angular2 还是很陌生。
我的 index.cshtml 看起来像这样。
<div class="container">
<div>
<h1>Welcome to the Angular 2 components!</h1>
</div>
<div class="row">
<MyAngular2Component>
<div class="alert alert-info" role="alert">
<h3>Loading...</h3>
</div>
</MyAngular2Component>
</div>
</div>
亲切的问候,
罗布
我发现从 MVC(或任何托管/启动页面)传入数据的最佳方法是将数据指定为引导组件上的属性,并使用ElementRef
直接检索值。
下面是从this answer派生的 MVC 示例,它指出不能将@Input
用于根级组件。
示例:
//index.cshtml
<my-app username="@ViewBag.UserName">
<i class="fa fa-circle-o-notch fa-spin"></i>Loading...
</my-app>
//app.component.ts
import {Component, Input, ElementRef} from '@angular/core';
@Component({
selector: 'my-app',
template: '<div> username: <span>{{username}}</span> </div>'
})
export class AppComponent {
constructor(private elementRef: ElementRef) {}
username: string = this.elementRef.nativeElement.getAttribute('username')
}
如果要检索不适合某个属性的更复杂的数据,可以使用相同的技术,只需将数据放入 HTML <input type='hidden'/>
元素或隐藏的<code>
元素中,然后使用纯 JS 来检索值。
myJson: string = document.getElementById("myJson").value
警告:直接从数据绑定应用程序(例如 Angular)访问 DOM 会破坏数据绑定模式,应谨慎使用。
您可能想要寻找与 AngularJS 相关的类似问题,而不是特定于 Angular 2 的问题,因为事情的主要要点保持不变:
在 Marius Schulz 的这篇文章中,您可以看到他序列化数据并使用它来填充模板 AngularJS value
组件:
<script>
angular.module("hobbitModule").value("companionship", @Html.Raw(Model));
</script>
可以使用类似的方法将一些数据注入到window.myNamespace.myServerData
,然后让 Angular2 在其他提供者中引导该值。
在 Roel van Lisdonk 的这篇文章中,再次使用了类似的方法来填充基于 AngularJS 的模板,并使用ng-init
指令:
<div ng-controller="main"
ng-init="resources={ textFromResource: '@WebApplication1.Properties.Resources.TextFromResource'}">
<h1>{{ title }}</h1>
{{ resources.textFromResource }}
</div>
正如第一篇文章所指出的,有一些事情需要考虑(粘贴在这里):
提醒一句:我将要使用的方法可能不太适合大量数据。 由于 JavaScript 数据被内联到 HTML 响应中,因此每次请求该页面时都会通过线路发送。
此外,如果数据特定于经过身份验证的用户,则无法再缓存响应并将其传递给不同的用户。 在考虑以这种方式使用 .NET 数据引导 Angular 应用程序时,请记住这一点。
如果您的服务页面已经是动态的服务器端,即如果它已经从服务器端数据中填充了位,那么第二部分可能不是什么问题。
HTH
您需要首先将您的服务和控制器捆绑在单独的模块文件中,并在控制器之前加载服务。 例如:
dist
|--services.js
|--controllers.js
然后你需要通过 ASP.NET MVC JavaScript 结果加载服务的 JavaScript 代码,这里你需要注入你的启动数据。
public class ScriptController: Controller
{
public ActionResult GetServices(){
string file= File.ReadAllText(Server.MapPath("~dist/services.js"));
//modify the file to inject data or
var result = new JavaScriptResult();
result.Script = file;
return result;
}
然后在 index.html 中加载脚本如下
<script src="/script/getservices"></script>
<script src="/dist/controller.js"></script>
通过这种方式,您可以在加载时将数据注入到 angular 代码中。 但是,即使这样也会由于获取视图、编译视图和将数据绑定到视图所花费的时间而对性能产生影响。 如果您使用服务器端渲染,初始加载性能仍然可以提高。
您可以使用@angular/core
公开的Input
函数,例如我有一个 Angular 2 组件来向应用程序的用户显示信息消息
我的 HTML 模板采用 Angular 2 Message
属性
<div class="alert alert-info col-lg-10 col-lg-offset-1 col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1">
<i class="fa fa-info-circle"></i> {{ Message }}
</div>
Message
属性作为输入传递给我的名为 informationmessage.component.ts 的 Angular 2 组件,例如
import { Component, Input } from '@angular/core';
@Component({
selector: 'informationmessage',
templateUrl: '../Templates/informationmessage.component.html'
})
export class InformationMessageComponent {
@Input() Message: string;
}
例如,然后我使用 HTML 页面中的属性绑定将数据传递给我的InformationMessageComponent
。
<informationmessage [Message]="InformationMessage"></informationmessage>
例如,您可以将上面示例中的InformationMessage
替换为从 MVC 控制器获取的数据
<informationmessage [Message]="@Model.InformationMessage"></informationmessage>
请注意:我没有测试这个场景,但没有技术原因使它不起作用,在一天结束时,您只是将一个值绑定到 Angular 2 属性。
src/ApplicationConfiguration.ts
export class ApplicationConfiguration {
public setting1: string;
public setting2: string;
}
src/main.ts
declare var config : ApplicationConfiguration;
var providers = [{ provide: ApplicationConfiguration, useValue: config }];
platformBrowserDynamic(providers).bootstrapModule(AppModule)
.catch(err => console.log(err));
源代码/索引.html
<script type="text/javascript">
var config = {setting1: "value1", setting2: "value2"};
</script>
src/app/app.component.ts
export class AppComponent {
private _config : ApplicationConfiguration;
constructor(config: ApplicationConfiguration) {
this._config = config;
}
}
我找到了一个更简单的解决方案。 不要试图从构造函数中获取属性! 改用ngOnInit()
钩子。 只要使用@Input()
修饰该属性,就可以访问该属性。 它似乎在调用构造函数时不可用。
组件 HTML:
<MyComponent [CustomAttribute]="hello"></MyComponent>
组件 TS:
export class MyComponentComponent {
@Input()
public CustomAttribute: string;
constructor() {}
ngOnInit() {
console.log("Got it! " + this.CustomAttribute);
}
}
进一步@Joseph Gabriel 的方法,如果您希望通过属性传递复杂对象,则在 MVC 中您应该将其序列化为string
,然后在角度侧使用JSON.Parse
对其进行JSON.Parse
序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.