Angularjs + MVC Routes with Partial Views

     Recently I've had the great opportunity to create something pretty awesome and I think it helped me seperate or clear up any confusion I had on project where I used two MVC frameworks on top of each other. Those two frameworks are usually AngularJs and MVC. It can be a little hairy especially if you're new to Angularjs but when you use them right web developing is be a snap.

Client Side
$routeProvider.when('/', {
    templateUrl: 'home/_home',
    controller: 'AppCtrl'
}).when('/product/:id', {
    templateUrl: function(params) {
        return 'home/_product/' +;
    controller: 'AppCtrl'
    redirectTo: '/'

  What's really important here is the route for product and the parameter (look where it takes id). The id can hookup to any middle tier and from there it can handed to a model bound partial view. You can even mix in angular html attributes since the page will be pulled in via ajax. Also you can ignore the _Home route that's just something I was playing around with.

Server Side
public PartialViewResult _Product(int id)
   var map = new String();
   for (var i =0; i< id; i++)
      map += i.ToString();
   return PartialView(map);

    I just made something up for the example but you can use anything so long as you're mapping is written out with the right parameters. You can use more complex parameters but I like to go the id route if I can.

    There are two files that make this work one is the partial view in Mvc called ~/Views/Home/_Product and in the Index page use a ng-view. Angular will pull in's partial view and leave the rest of routing to the server if not definited. A word of caution, many times when I was trying to get this to work I created a "routing infinite loop". So just watch out for that and things should be good.


Mapping AngularJS Routes Onto URL Parameters And Client-Side Events
AngularJS Routes |

Popular posts from this blog

Nginx Best Practices Extended

Installing Windows on Acer chromebook 15 cb3-532

Entity Framework: ToListAynsc & WhereAsync