使用.net MVC的Angular路由

Angular Route with .NET MVC

本文关键字:Angular 路由 MVC net 使用      更新时间:2023-09-26

我正在Mono上使用AngularJS构建一个。net MVC。

我有一个简单的HomeController和一个简单的return View(),加载我的项目的主页。

我的主Index.cshtml看起来像:

<body ng-controller="AppController"> 
  <ul>
    <li><a href="/#/routeOne">Route One</a></li>
    <li><a href="/#/routeTwo">Route Two</a></li>            
    <li><a href="/#/routeThree">Route Three</a></li>
  </ul>
</body>

我的javascript设置如下:

(function () {
    var app = angular.module('app', ['ngRoute']);
    app.config(function ($routeProvider) {
        $routeProvider.when('/routeOne', {
            templateUrl: 'RoutesDemo/One'
        })
        .when('/routeTwo', {
            template: 'RoutesDemo/two'
        })
        .when('/routeThree', {
            template: 'RoutesDemo/three'
        });
    });
        //var app = angular.module('app');
    app.controller('AppController', function ($scope) {
        $scope.test = 'Hello World';
    });
})();

所以在这一点上,我的预期行为是,如果我点击Route One链接,应用程序应该调用RoutesDemoController's One方法,它呈现一些部分视图:它工作!

但这并没有发生

相反,只有链接改变了,但我在浏览器或网络选项卡中没有看到任何活动。

我错过了一个步骤吗?

编辑:

我正在查看的主页点击Index.cshtmllocalhost:8080

我能够点击localhost:8080/RoutesDemo/One,它返回我的部分视图。

当我点击Route One的锚链接时,我的url是http://localhost:8080/#/routeOne

你没有一个出口供你的路由模板写入。Angular为此提供了一个特殊指令ng-view。当路由提供程序处理特定的路由时,ng-view元素的.innerHtml将动态地替换为templatetemplateUrl属性的内容。https://docs.angularjs.org/api/ngRoute/directive/ngView

把你的索引改成这样:

<body ng-controller="AppController"> 
  <ul>
    <li><a href="/#/routeOne">Route One</a></li>
    <li><a href="/#/routeTwo">Route Two</a></li>            
    <li><a href="/#/routeThree">Route Three</a></li>
  </ul>
  <ng-view />
</body>