【问题标题】:How to using MVC views (*.cshtml) as templates in Angular 2?如何在 Angular 2 中使用 MVC 视图 (*.cshtml) 作为模板?
【发布时间】:2019-03-15 14:04:19
【问题描述】:

大家好,我想知道如何在 Angular 2 中使用 MVC 视图而不是模板。 在 Angular 2
中,我使用的是 RouteProvider:

$routeProvider.
when('/BusinessLookup', {
    templateUrl: 'Home/BusinessLookup',
    controller: 'BusinessLookupController'
});

我如何使用$Scope 处理元素值。

【问题讨论】:

    标签: angular


    【解决方案1】:

    你可以在templateURL中直接调用你的cshtml视图

    import {Component, OnInit} from "angular2/core";
    
    @Component({
        selector: "mvc",
        templateUrl: "/partial/message"
    })
    export class MvcComponent implements OnInit {
        message: string;
    
        constructor() { }
    
        ngOnInit() {
            this.message = "The '/partial/message' path was used as the Angular2 'templateUrl'. However, this routes through the 'PartialController' hitting the 'Message' action and is served after standard MVC pre-processing. Likewise, there is a 'message' property bound to the <blockqoute> element."
        }
    }
    

    部分/Message.cshtml

    @{
        ViewBag.Title = "MVC";
    }
    <mvc>
        <blockquote *ngIf="message">{{message}}</blockquote>
    </mvc>
    

    【讨论】:

      【解决方案2】:

      您要求的内容称为Isomorphic Javascript。基本上,您不能在客户端运行 Razor,但可以在服务器上运行 javascript。

      您正在寻找的内容可能更多在nodejs 范围内。这可能可以通过改变架构来完成,但这意味着改变问题。

      【讨论】:

      • 我以前用它来创建使用 AngularJS 1 的 SPA 项目,它的工作。但我想将我的项目转移到使用 Angular 2 而不是 AngularJs1。这就是我想要的。
      • 您可以毫无问题地在其中创建带有 AngularJS(1 或 2)的 MVC 视图。您的问题非常广泛且难以理解。
      • 这就是我想要创建 MVC 视图并使用 Angular 2 处理它们。但我的问题是我怎么能这样做,因为我找不到任何参考可以帮助我从 Angular 1 移动到 Angular 2。
      • 这是一个可能对您有所帮助的链接,但除此之外,这与 asp.net-mvc-6 paislee.io/migrating-to-angularjs-2-0 无关
      【解决方案3】:

      当然可以将cshtml渲染为模板!

      @Component({
          moduleId: module.id,
          templateUrl: "/YourController/YourAction" 
      })
      

      当需要模板时,Angular 会向 'templateUrl' 发出 http 请求。

      如果该 url 被解析为 MVC Action,则 IIS 调用传统的 MVC 管道,该管道可以使用 Razor 解析 cshtml,最后返回 html,对 angular 有效

      【讨论】:

        【解决方案4】:

        是的,你可以做到。

        import { Component } from '@angular/core';
        @Component({
            selector: 'my-app',
            templateUrl: '/Student/Register',
        })
        export class AppComponent  { name = 'first Angular demo'; }
        

        在 Views 创建目录 Student 添加文件 Register.cshtml

        Hello {{name}}
        

        【讨论】:

          猜你喜欢
          • 2017-06-23
          • 2017-02-16
          • 1970-01-01
          • 2016-05-03
          • 1970-01-01
          • 2016-09-07
          • 2012-06-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多