Angular Routing with ASP MVC

2019-09-13 18:34发布

问题:

I have an MVC test project I am working on to see if I can get angular routing to work with it.

What I mean by work with it is that I want to be able to have a landing page for my app: www.testapp.com

Then when people log in I want MVC to route them to testapp.com/Dashboard/#/and then I want to be able to use ng-view to load pages with Angualar like so: testapp.com/Dashboard/#/PageOne, testapp.com/Dashboard/#/PageTwo, etc.

Here is what I have tried: main.js:

angular.module('App', ['ngRoute', 'ngResource']);

angular.module('App').config(function ($routeProvider) {
    $routeProvider
    .when('/Dashboard', {
        templateUrl: 'Dashboard/Index'
    })
    .when('/PageOne', {
        templateUrl: 'Dashboard/PageOne'
    })
});

~/Views/Home/Index.cshtml was my landing page that did not use angular routing it just had ActionLinks to Login and Register

~/Views/Dashboard/Index.cshtml is where I used ng-app and ng-view and I had links like so: <a href="/#/Dashboard">Dashboard</a>, <a href="/#/PageOne">Page One</a>

The problem is that when I go to testapp.com/Dashboard when it loads the URL turns into testapp.com/Dashboard#/ rather than testapp.com/Dashboard/#/

The other problem is that when I click on my links it goes straight back to the Home/Index and the URL is like so: testapp.com/#/PageOne but the Home is being displayed

in my RouteConfig.cs file it is just the default:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

So my question is what is wrong with my code here that makes it not function like I want it to? What do I have to add/change?

Thank you!

回答1:

So I figured out the issue was with the way I was writing my links. Once my actual angular app was loaded (I was at the Dashboard rather than the landing page where angular is initialized) I had to change my anchor tag hrefs from \#\{Route} to '/Dashboard/#/{Route}'. Here is my updated angular route config:

angular.module('App').config(function ($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: 'Index'
    })
    .when('/PageOne', {
        templateUrl: 'PageOne'
    })
});

This completely fixed my problem so I can now have angular routing take over the show when it needs to and also have MVC ActionLinks in my application as well.

Hope this helps someone else!

NOTE

I did not change anything in my MVC RouteConfig.cs you can leave the default. Also I had to get rid of ViewStart because that was messing things up.