Abjo Abjo - 6 months ago 34
Javascript Question

AngularJs $routeProvider is not working with MVC

When I am using $routeProvider with MVC.Net its not working.

I am using Write up Backend example for MVC.Net.
Following is the route I am using


config(function($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'home/listitem' }).
when('/home', { controller: ListCtrl, templateUrl: 'home/listitem' }).
when('/edit/:projectId', { controller: EditCtrl, templateUrl: '/home/detail' }).
when('/new', { controller: CreateCtrl, templateUrl: '/home/detail' }).
otherwise({redirectTo:'/'});
});


but unfortunately it is not calling listitem or details.

Answer

This works fine. Setup your RouteConfig.cs as follows:

        // Will handle partial page view requests
        routes.MapRoute(
            name: "Partials",
            url: "partials/{controller}",
            defaults: new { controller="Home", action = "Index" }
        );

        // Will handle all other requests by sending it to the main controller
        routes.MapRoute(
            name: "Application",
            url: "{*url}",
            defaults: new { controller = "Main", action = "Index" }
        );

Then your angular config for routing like this:

 .config(['$routeProvider', '$locationProvider',
        function($routeProvider, $locationProvider) {
            $routeProvider
                .when('/', {
                    templateUrl: '/partials/home',
                    controller: 'HomeController'
                })
                .when('/home', {
                    templateUrl: '/partials/home',
                    controller: 'HomeController'
                })
                .when('/gallery', {
                    templateUrl: '/partials/gallery',
                    controller: 'GalleryController'
                });
                .when('/services', {
                    templateUrl: '/Services',
                    controller: 'ServicesController'
                });

            // NOTE: This part is very important
            $locationProvider.html5Mode(true);
        }
    ]);

And your MVC controllers:

public class MainController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return PartialView("_Home");
    }
}

public class GalleryController : Controller
{
    public ActionResult Index()
    {
        return PartialView("_Gallery");
    }
}

Put your partial views in the shared folder.

Now, behind the scenes you can do everything like you normally would with an MVC controller and view, including razor and all that.