Angularjs + Asp.net 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 Asp.net 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/' + params.id;
    },
    controller: 'AppCtrl'
}).otherwise({
    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.


Files
    There are two files that make this work one is the partial view in Asp.net Mvc called ~/Views/Home/_Product and in the Index page use a ng-view. Angular will pull in Asp.net'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.

Example: http://trainapp.anthonyfassett.com

Resources
Mapping AngularJS Routes Onto URL Parameters And Client-Side Events
AngularJS Routes | tutorials.jenkov.com

Popular posts from this blog

UI-Bootstrap Collapsible Sticky Footer

Installing Windows on Acer chromebook 15 cb3-532

Aspetcore: NLog with Postgresql