简体   繁体   中英

Binding from mvc model to angular2 component (Components in mvc project)

I could use some help, figure out how to pass model data from mvc application to a angular2 component running inside mvc.

Lets say I have a cs.html file that has an component

<my-app></my-app>

This will load the angular2 component. I need to generate some binding to keep mvc models intact with my angular2 models.

First of all, I'm trying to pass a model to the component via the Input property.

CSHTML file:

In the top of my cshtml file, I have:

@model MainModel
<script>
    var model = @Html.Json(Model.Form.PassengerModel);
</script>

I want to pass this model to my angular2 component. What I have tried are:

<my-app passengerModel="model"></my-app>

Angular2 component:

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

@Component({
    selector: 'my-app',
    templateUrl: './Content/Scripts/angular2components/app.component.html',
})
export class AppComponent {
    @Input() passengerModel: PassengerModel;

    constructor() {
        console.log("Model loaded?: " + this.passengerModel);

    }

}

export class PassengerModel {
    constructor(
        public Adults: number,
        public Children: number
    ) { }
}

The problem is that the model is undefined always. Is there any way to pass a model in to the component?

The problem you have outlined above is that your binding is not correct for the context you are attempting to use it in.

<my-app passengerModel="model"></my-app>

The above line is telling Angular to bind passengerModel inside your my-app component to a property on the host component named model. This means the page (component) which hosts your my-app component should be a component with a property named model. You have created a global variable which is not in the scope of your host component. Angular2 specifically isolates the scope of each component so that you do not accidentally introduce unwanted side effects.

Save yourself some pain an anguish and embrace Angular fully. Ditching your MVC Page Controllers and moving to WebApi service calls will yield better results and save you the need to translate the model manually among other issues you will run into going down the mixed route.

Considerations:

  • @Html.Json will ultimately cause your data to be exposed directly in your script tag. This could be a security risk if the data is sensitive and if you start using MVC Model bindings in the page alongside Angular bindings they will fight each other.
  • Basically these approaches are diametrically opposed as ASP.NET MVC is a server side approach and Angular is a client side approach. Mixing them in the same application will always be awkward at best.
  • WebApi gives you the JSON serialization more or less for free. Your MVC model is automatically serialized to JSON by the framework when returning an HttpAction. If you are trying to avoid converting your ASP.NET MVC views to Angular Components then I understand. You may not have a choice but if you do I would steer clear of mixing these two.
[HttpGet]
[AcceptVerbs["GET"]
[Route("passengers/{id:int}")]
public IHttpActionResult GetPassenger(int id)
{
    // For illistration...
    try
    {
        var passengerModel = PassengerService.LoadPassenger(id);
        return Ok(passenger);
    }
    catch(Exception e)
    {
        return InternalServerError(e);
    }
}

https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

// I would normally put this in the environemnt class..
private passengerUrl = 'api/passengers';  // URL to web api

constructor(private http: Http) { }

getPassenger(id: number): Promise<Passenger> {
    return this.http.get(`this.passengerUrl/${id}`)
        .toPromise()
        .then(response => response.json() as Passenger)
        .catch(this.handleError);
}

private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM