使用ASP.NET MVC 6和AngularJS在SPA中进行路由 [英] Routing in SPA with ASP.NET MVC 6 and AngularJS

查看:113
本文介绍了使用ASP.NET MVC 6和AngularJS在SPA中进行路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例MVC6单页应用程序,其中有一个视图,我想在其中使用ngRoute加载2个Angular局部视图。您可以在 GitHub

I have a sample MVC6 single page app with one view in which I want to load 2 Angular partials using ngRoute. You can have a look at it at GitHub

应用程序中有3个URL:

There are 3 URLs in the app:


  1. localhost-Index.cshtml

  2. localhost / games-具有Angular的gamelist.html局部的Index.cshtml

  3. localhost / games / 2-具有Angular的game.html局部的Index.cshtml

路由配置如下:

MVC:

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}");

            routes.MapRoute("gamelist", "games", new { controller = "Home", action = "Index"});
            routes.MapRoute("gameWithId", "games/2", new { controller = "Home", action = "Index" });
        });

角度:

myApp.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/games', {
            templateUrl: 'partials/gameslist.html',
            controller: 'GameController',
            controllerAs: 'ctrl'
        })
        .when('/games/:gameId', {
            templateUrl: 'partials/game.html',
            controller: 'GameController',
            controllerAs: 'ctrl'
        });

    $locationProvider.html5Mode(true);
}]);

只要我从首页 /启动应用程序,然后使用页面上的链接导航到局部。问题是,如果我通过在地址栏中键入它来启动应用程序,则UR​​L#3(localhost / games / 2)无法正常工作。 URL#2(/ games /)起作用。

It all works perfectly fine as long as I start the app from the home page '/' and then navigate to the partials using the links on the page. The problem is that the URL #3 (localhost/games/2) does not work if I start the app from it, by typing it in the address bar. The URL #2 (/games/) does work.

#3无效的原因是MVC从网址中删除了 /游戏部分,而Angular获得的只是 / 2。如果您运行示例应用,则会看到 $ location.path = / 2。当然,Angular无法使用该路径进行映射,并且不会渲染任何局部。所以我的问题是-如何使MVC返回客户端的完整路径,以便Angular可以映射它?

The reason why #3 does not work is that MVC removes '/games' part from the URL and what Angular gets is just '/2'. If you run the sample app, you will see that '$location.path = /2'. Of course Angular cannot map using that path and no partial is rendered. So my question is - how to make MVC return the full path to the client so that Angular can map it?

推荐答案

链接#3在浏览器的地址栏中起作用,我在Angular中关闭了 html5Mode,并使链接基于#。

To make link #3 work from the browser's address bar, I turned off "html5Mode" in Angular and made links #-based.

这篇关于使用ASP.NET MVC 6和AngularJS在SPA中进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆