簡體   English   中英

如何將數據從 asp.NET MVC 傳遞到 Angular2

[英]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 的問題,因為事情的主要要點保持不變:

  • 您希望服務器端 Razor 引擎呈現某種視圖(即直接呈現 HTML 或 JS)
  • 此視圖包含一個 JS 模板,其中部分內容是從服務器模型實例或無論如何服務器數據(例如資源、字典等)填充的
  • 為了從 Razor 正確填充 JS 變量,C# 服務器端數據必須正確序列化為 JSON 格式

在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM