简体   繁体   English

从mvc模型绑定到angular2组件(mvc项目中的组件)

[英]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. 我可以使用一些帮助,弄清楚如何将模型数据从mvc应用程序传递到在mvc中运行的angular2组件。

Lets say I have a cs.html file that has an component 可以说我有一个包含组件的cs.html文件

<my-app></my-app>

This will load the angular2 component. 这将加载angular2分量。 I need to generate some binding to keep mvc models intact with my angular2 models. 我需要生成一些绑定以使mvc模型与我的angular2模型保持完整。

First of all, I'm trying to pass a model to the component via the Input property. 首先,我试图通过Input属性将模型传递给组件。

CSHTML file: CSHTML文件:

In the top of my cshtml file, I have: 在我的cshtml文件的顶部,我有:

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

I want to pass this model to my angular2 component. 我想将此模型传递给我的angular2组件。 What I have tried are: 我尝试过的是:

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

Angular2 component: Angular2组件:

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. 上一行告诉Angular将my-app组件内的passengerModel绑定到名为model的主机组件上的属性。 This means the page (component) which hosts your my-app component should be a component with a property named model. 这意味着承载my-app组件的页面(组件)应该是具有名为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. Angular2专门隔离了每个组件的范围,因此您不会意外引入有害的副作用。

Save yourself some pain an anguish and embrace Angular fully. 避免痛苦和痛苦,完全拥抱Angular。 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. 抛弃您的MVC页面控制器并转到WebApi服务调用将产生更好的结果,并且省去了手动转换模型的麻烦,因为您会遇到其他问题。

Considerations: 注意事项:

  • @Html.Json will ultimately cause your data to be exposed directly in your script tag. @ Html.Json最终将导致您的数据直接在脚本标签中公开。 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. 如果数据很敏感,并且您开始在页面中与Angular绑定一起使用MVC Model绑定,那么这可能会带来安全风险。
  • Basically these approaches are diametrically opposed as ASP.NET MVC is a server side approach and Angular is a client side approach. 基本上,这些方法是截然相反的,因为ASP.NET MVC是服务器端方法,而Angular是客户端方法。 Mixing them in the same application will always be awkward at best. 在同一个应用程序中混合它们总是很尴尬。
  • WebApi gives you the JSON serialization more or less for free. WebApi免费为您提供或多或少的JSON序列化。 Your MVC model is automatically serialized to JSON by the framework when returning an HttpAction. 当您返回HttpAction时,框架会将您的MVC模型自动序列化为JSON。 If you are trying to avoid converting your ASP.NET MVC views to Angular Components then I understand. 如果您试图避免将ASP.NET MVC视图转换为Angular Components,那么我理解。 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 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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