asp .net navigating between different pages using angularJS in localhost

375 views Asked by At

I am trying to learn more about angularJS and I came across problem with routing.

I am developing a ASP .NET project in Visaul Studio. I am running the project in localhost on Google Chrome.

Here is how my project directory:

enter image description here

Here is my Index.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Test AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

    <!--base href="@Url.Content("~/")" /--><!--Found it in a post. Didnt help-->
</head>

<body ng-app="myApp">

    <p><a href="#/">Main</a></p>
    <a href="#Groups">Groups</a>

    <div ng-view></div>

    <script>
        var app = angular.module("myApp", ["ngRoute"]);        
        app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
            //$locationProvider.html5Mode(false);            
            $routeProvider
            .when("#", {
                templateUrl: "Index.cshtml"
            })
            .when("/Groups", {
                templateUrl: '/Views/AngularViews/Groups.cshtml',
                controller: 'GroupsController'
            })
        }]);

    </script>

</body>
</html>

Here is my Groups.cshtml

<section id="Groups_Controller" class="" ng-controller="GroupsController">
<h2>_Groups</h2>
<div>
    This is the Groups page!!!
    {{5+5}}
</div>
</section>

<script>
   function GroupsController($scope, $http, $modal, $timeout, $location) {
   };
</script>

This is how the page looks when I run the application. enter image description here

When I click on Groups page. I get this error on the console: enter image description here

1

There are 1 answers

0
Claies On

You are trying to treat a server side .cshtml page as a client side .html partial, which won't work. The server is actively rejecting the .cshtml page, because .cshtml pages are meant exclusively for rendering by the server, usually Razor.

You should change the file to .html in order for it to be rendered by Angular instead.

However, you also have another issue, in that you can't declare your Angular controller inside the partial; The router will be trying to find the controller before the partial has been loaded, and the controller won't exist.

Also, you shouldn't use controller: on your route and ng-controller inside your partial both at the same time, since each one of these will attempt to create an instance of your controller, leading to issues with data bindings.