Rob Van Pamel
Rob Van Pamel

Reputation: 744

How to pass data from asp.NET MVC to Angular2

What is the best way to pass data from an ASP.NET MVC controller to an Angular 2.0 component? For example, we use the ASP.NET MVC Model and would like to send a JSON version of it to Angular to use it in Angular.

When the controller is serving the view, we can already push some data to Angular2 (the model). So additional AJAX call to fetch that data is not required.

However, I am struggling to "inject" it into the Angular component. How do you do this? Any good references for this? As you may have noticed, I'm quite new to Angular2.

My index.cshtml looks like this.

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

Kind regards,

Rob

Upvotes: 20

Views: 20431

Answers (7)

JPB
JPB

Reputation: 1

Further to @Joseph Gabriel's approach, if you want a complex object to be passed via an attribute, in MVC you should serialize it to a string, and then in the angular side de-serialize it using JSON.Parse.

Upvotes: 0

user9742894
user9742894

Reputation:

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

src/index.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;

  }

}

Upvotes: 1

Eraph
Eraph

Reputation: 1029

I found a much simpler solution. Don't attempt to get the attribute from in the constructor! Use the ngOnInit() hook instead. The property will be accessible as long as it has been decorated with @Input(). It just appears that it is not available by the time the constructor is called.

Component HTML:

<MyComponent [CustomAttribute]="hello"></MyComponent>

Component TS:

export class MyComponentComponent {
    @Input()
    public CustomAttribute: string;

    constructor() {}

    ngOnInit() {
        console.log("Got it! " + this.CustomAttribute);
    }
}

Upvotes: 0

Joseph Gabriel
Joseph Gabriel

Reputation: 8520

The best way that I have found to pass data in from MVC (or any hosting/startup page) is to specify the data as an attribute on the bootstrapped component, and use ElementRef to retrieve the value directly.

Below is an example for MVC derived from the this answer, which states that it is not possible to use @Input for root-level components.

Example:

//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')
}

If you want to retrieve more complex data that is not suitable for an attribute, you can use the same technique, just put the data in a HTML <input type='hidden'/> element or a hidden <code> element, and use plain JS to retrieve the value.

myJson: string = document.getElementById("myJson").value

Warning: Access the DOM directly from a data-bound application such as Angular, breaks the data-binding pattern, and should be used with caution.

Upvotes: 16

Andre Lombaard
Andre Lombaard

Reputation: 7105

You can use the Input function exposed by @angular/core, I have for example an Angular 2 component to display information messages to the user of the application

My HTML template take an Angular 2 Message property

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

The Message property is passed as an input to my Angular 2 component named informationmessage.component.ts, for example

import { Component, Input } from '@angular/core';

@Component({
    selector: 'informationmessage',
    templateUrl: '../Templates/informationmessage.component.html'
})
export class InformationMessageComponent {
    @Input() Message: string;
}

I then pass the data to my InformationMessageComponent using property binding in the HTML page, for example.

<informationmessage [Message]="InformationMessage"></informationmessage>

You can replace InformationMessage in the above example with the data that you get from your MVC controller for example

<informationmessage [Message]="@Model.InformationMessage"></informationmessage>

Please note: I did not test this scenario, but there is no technical reason for it not working, at the end of the day you are just binding a value to an Angular 2 property.

Upvotes: 1

superjos
superjos

Reputation: 12745

You might want to look for similar questions related to AngularJS, not Angular 2 specific, as the main gist of the thing remains the same:

  • you want your server-side Razor engine to render some kind of view (i.e. HTML or JS directly)
  • this view contains a JS template where part of the content is filled from a server model instance or anyway server data (e.g. a resource, dictionary, etc.)
  • in order to properly fill a JS variable from Razor, C# server-side data has to be properly serialized into a JSON format

In this post by Marius Schulz you can see as he serializes the data and uses that to fill a template AngularJS value component:

<script>
  angular.module("hobbitModule").value("companionship", @Html.Raw(Model));
</script>

Something similar could be made to inject some data e.g. into window.myNamespace.myServerData, and then have Angular2 bootstrap that value among other providers.

In this post by Roel van Lisdonk, a similar approach is used, again, to fill an AngularJS-based template, with that ng-init directive:

<div ng-controller="main"
     ng-init="resources={ textFromResource: '@WebApplication1.Properties.Resources.TextFromResource'}">
  <h1>{{ title }}</h1>
  {{ resources.textFromResource }}
</div>

As the first post points out, there's something to think about (pasting here):

A word of caution: The method I'm about to use is probably not a good fit for large amounts of data. Since the JavaScript data is inlined into the HTML response, it's sent over the wire every single time you request that page.

Also, if the data is specific to the authenticated user, the response can't be cached and delivered to different users anymore. Please keep that in mind when considering to bootstrap your Angular Apps with .NET data this way.

The second part may be less of an issue if your served page is already dynamic server-side, i.e. if it already has bits filled in out of server-side data.

HTH

Upvotes: 2

Jigar
Jigar

Reputation: 544

You need to first bundle your services and controllers in separate module files and load services before controllers. For example:

dist
|--services.js
|--controllers.js

Then you need to load the JavaScript code of the Services via ASP.NET MVC JavaScript result, here you need to inject your startup data.

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

Then in the index.html load the scripts as follows

<script src="/script/getservices"></script>
<script src="/dist/controller.js"></script>

This way you can inject data into angular code while loading. However, even this has a performance impact due to time spent on fetching the view, compiling the view, and binding data to the view. For an initial load performance can still be improved if you use Server Side Rendering.

Upvotes: 1

Related Questions