Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I’m working on a new ASP.NET MVC and AngularJS application that is intended to be a collection of SPAs. I’m using the MVC areas concept to separate each individual SPA, and then I’m using AngularJS within each MVC area to create the SPA.

Since I’m new to AngularJS and haven’t been able to find an answer regarding combining both MVC and AngularJS routing, I thought I’d post my question here to see if I could get some help.

I have the standard MVC routing setup, which serves up each MVC area.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        routes.AppendTrailingSlash = true;
    }

This works fine and gives me URLs like:

http://servername/Application1/
http://servername/Application2/

Now, within each application area, I’m trying to use AngularJS routing, also using $locationProvider.html5Mode(true); so that I get the client-side routing within each area, something like:

http://servername/Application1/view1
http://servername/Application1/view2
http://servername/Application2/view1/view1a
http://servername/Application2/view2/view2a
http://servername/Application2/view3

Here’s my AngularJS routing snippet for Application1:

app1.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    var viewBase = '/Areas/Application1/app/views/';
    $routeProvider
        .when('/Application1/view1', {
            controller: 'View1Controller',
            templateUrl: viewBase + 'view1.html'
        })
        .when('/Application2/view2', {
            controller: 'View2Controller',
            templateUrl: viewBase + 'view2.html'
        })
        .otherwise({ redirectTo: '/Application1/view1' });
    $locationProvider.html5Mode(true);
}]);

So, initially, it seems to work (at least the URL looks correct). But, when I start navigating between areas or views within an area, or even if I refresh, something gets “lost” and things don’t work. The URL still looks correct but views aren’t found and aren’t getting loaded correctly.

Any help/guidance on how to make ASP.NET MVC and AngularJS routing work together to give me the scenario described above?

Thanks!!!

share|improve this question

3 Answers 3

ASP.NET MVC and AngularJS routing

In a classic ASP.NET MVC application, stepping between parts of the application usually requires a trip to the web server to refresh the entire contents of the page. However, in a Single Page Application (SPA), only elements within the page are updated giving the user a better, more responsive experience. In classic asp.net mvc implementation may still make transitions to other sections of the application with a full page refresh,but generally a single page manages the application’s functionality through dynamic views and web service (AJAX) calls.AngularJS supports dynamic views through routes and the ngView directive and your MVC application would provide the partial views that the ngView directive will dynamically load.

 public class HomeController : Controller  
   {  
     public ActionResult Index()  
     {  
       return View();  
     }  
     public ActionResult Home()  
     {  
       return PartialView();  
     }  
     public ActionResult About()  
     {  
       return PartialView();  
     }  
     public ActionResult Contact()  
     {  
       return PartialView();  
     }  
   }  

App.js this is the file which is going to have the AngularJS application module declared in it. Also the state navigation declared.

'use strict';  
 var app = angular.module('App',['ngRoute']);  
 app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {  
     $routeProvider.when('/', {  
       templateUrl: '/Home/Home',  
       controller: 'homeCtrl',  
     });  
     $routeProvider.when('/About', {  
       templateUrl: '/Home/About',  
       controller: 'aboutCtrl',  
     });  
     $routeProvider.when('/Contact', {  
       templateUrl: '/Home/Contact',  
       controller: 'contactCtrl'  
     });  
     $routeProvider.otherwise({  
       redirectTo: '/'  
     });  
   }]);

here is good example angularjs routing integration with source code http://aspmart.blogspot.com/2015/11/angularjs-routing-recipe-with-classic.html

share|improve this answer
up vote 22 down vote accepted

Thanks for the answer, agbenyezi. I looked at the article you provided but it only got me back to where I was anyway.

However, I was able to figure it out and get it working. The answer turned out to be relatively simple, but it took some time and a lot of searching around. Anyway, since I am using MVC areas, navigating to a URL of http://servername/Application1/view[x] (where Application1 is the MVC controller (in the area) and view1, view2, view3, etc. are Angularjs views), the MVC part of the overall application was getting confused and trying to find an action named view[x] in the Application1 controller (which doesn't exist).

So, in the area's AreaRegistration class (where it's defining specific routes for the area), I just needed to add a kind of catch-all route before any default MVC routes to always force it to the Index action on the Application controller. Something like:

        // Route override to work with Angularjs and HTML5 routing
        context.MapRoute(
            name: "Application1Override",
            url: "Application1/{*.}",
            defaults: new { controller = "Application1", action = "Index" }
        );

Now, when I navigate to http://servername/Application1/view[x] it routes to the Application1 MVC controller, Index action, and then Angularjs takes over routes to the different views, all while having the HTML5 routing construct in the URL.

Hope that helps others.

Thanks!

share|improve this answer
    
I would like to know how you organized angular JS and view code, ist it all in the scripts folder? And what do your <script tags refer to? application1/scripts/app ??? – spankmaster79 Dec 9 '14 at 16:15
    
What will happen if we again call action from Angular Ajax like (/Application1/Edit/2). Will it again redirect to index? – Murali Murugesan Apr 12 at 17:50

Check this article on Dave Baskin's blog:

http://www.wintellect.com/blogs/dbaskin/angularjs-mvc-cookbook-simple-routing

share|improve this answer
    
link-only answer is not good on SO. – jogo Nov 29 at 11:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.