0

I am trying to basically connect a SQL server DB to my angular application using .NET MVC. I initially built the app on Plunker (demo) and used a factory class for temp data, but now I am trying to implement it in MVC with real db data. My problem is that I am getting confused on Controllers, since MVC has a controller itself along with AngularJS's own controllers and I am not sure how to connect the two.

What I have thus far is the following.

MVC Controller (condensed)

public class TestController : Controller
{
   private MoviesEntities db = new MoviesEntities();
        public ActionResult account()
        {
            return View(db.Users.ToList().OrderBy(x => x.name));
        }
}

MVC View

@model IEnumerable<WebApplication2.Entities.User>

@{
    ViewBag.Title = "account";
    Layout = "~/Views/Shared/_LayoutTest.cshtml";
}

@Styles.Render("/Content/style.css")
<div ng-app="app">
    <div ng-controller="AccountController">
        <input type="text" ng-model="search.$">
        <table class="table table-striped">
            <tr ng-repeat="actors in Model">
                <td>{{actors.name}}</td>
                <td>{{actors.summoner}}</td>
            </tr>
        </table>
    </div>
</div>

@Scripts.Render("~/Scripts/angular.js")
@Scripts.Render("~/Scripts/angular-route.min.js")
@Scripts.Render("~/Scripts/app.js")

Now at this point I tried adding a reference to my app.js file but no data is shown or displayed, just a table with {{actors.name}} and {{actors.summoner}}. I have been searching and trying to find some tutorial on this basic implementation but cannot find a thing. If someone could show me what to do and explain why this isn't working that'd be awesome! I think the use of Controllers is just throwing me off, and I am not sure how to turn my factory in app.js into holding the database table values.

app.js (plunker demo of what I am trying to implement onto MVC now -> Demo

var app = angular.module("app", ['ngRoute']);

app.config(function ($routeProvider) {
    $routeProvider

    .when('/', {
        templateUrl: 'pages/home.html',
        controller: 'HomeController'
    })

    .when('/home', {
        templateUrl: 'pages/home.html',
        controller: 'HomeController'
    })

    .when('/login', {
        templateUrl: 'pages/login.html',
        controller: 'LoginController'
    })

    .when('/account', {
        templateUrl: 'pages/account.html',
        controller: 'AccountController'
    })

    .when('/unknown', {
        templateUrl: 'pages/unknown.html',
        controller: 'UnknownController'
    })
      .otherwise({
          redirectTo: '/unknown'
      });
});


app.factory('userService', function () {
    return {
        users: [{
            name: "John",
            password: "12345",
            email: "[email protected]",
            phone: "238-491-2138"
        }, {
            name: "Austin",
            password: "intern",
            email: "[email protected]",
            phone: "138-490-1251"
        }, {
            name: "Sally",
            password: "noob",
            email: "[email protected]",
            phone: "243-421-0738"
        }, {
            name: "Bilbo",
            password: "Baggins",
            email: "[email protected]",
            phone: "158-491-2138"
        }, {
            name: "Marco",
            password: "Wafflez",
            email: "[email protected]",
            phone: "935-491-2654"
        }, {
            name: "Sam",
            password: "Adams",
            email: "[email protected]",
            phone: "743-491-2131"
        }, {
            name: "Willy",
            password: "W0nk4",
            email: "[email protected]",
            phone: "682-491-2983"
        }]

    };
});

app.controller('LoginController', function ($scope, $location, userService, $timeout) {
    $scope.credentials = {
        username: "",
        password: ""
    };
    $scope.credentialsR = {
        username: "",
        password: ""
    };

    $scope.login = function () {
        for (var i = 0; i < userService.users.length; i++) {
            if (userService.users[i].name.toLowerCase() === $scope.credentials.username.toLowerCase()) {
                if (userService.users[i].password === $scope.credentials.password) {
                    $scope.messageLogin = "Success!";
                    $timeout(function () {
                        $timeout(function () {
                            $location.path("/home");
                        }, 500)
                        $scope.messageLogin = "Redirecting...";
                    }, 500)
                } else {
                    $scope.messageLogin = "Incorrect login details";
                }

                return;
            }
        }

        $scope.messageLogin = "Username does not exist";
    };

    $scope.checkName = function () {
        for (var i = 0; i < userService.users.length; i++) {
            if (userService.users[i].name.toLowerCase() === $scope.credentialsR.username.toLowerCase()) {
                $scope.messageRegister = "Taken";
                return;
            }
        }

        $scope.messageRegister = "Available";
    };
});

app.controller('HomeController', function ($scope) {
    $scope.title = "Home";
});

app.controller('AccountController', function ($scope, userService, $resource) {
    var Users = $resource('/Test/')
    $scope.userList = userService.users;
});

app.controller('UnknownController', function ($scope) {

});

I also used NuGet to install AngularJS, so I believe referencing angular.js at the bottom should be fine as well.

Started building this layout from ngRepeat and Filtering Data

Current Error(s)

Error: [$injector:unpr] Unknown provider: $resourceProvider <- $resource
http://errors.angularjs.org/1.2.21/$injector/unpr?p0=%24resourceProvider%20%3C-%20%24resource
    at http://localhost:56087/Scripts/angular.js:78:12
    at http://localhost:56087/Scripts/angular.js:3776:19
    at Object.getService [as get] (http://localhost:56087/Scripts/angular.js:3904:39)
    at http://localhost:56087/Scripts/angular.js:3781:45
    at getService (http://localhost:56087/Scripts/angular.js:3904:39)
    at invoke (http://localhost:56087/Scripts/angular.js:3931:13)
    at Object.instantiate (http://localhost:56087/Scripts/angular.js:3951:23)
    at http://localhost:56087/Scripts/angular.js:7244:28
    at http://localhost:56087/Scripts/angular.js:6635:34
    at forEach (http://localhost:56087/Scripts/angular.js:332:20) 

1 Answer 1

3

You need to include angular-route.min.js or angular-route.js after angular.js. If you do not have it on your Scripts folder, check NuGet.

Try also using angular-resource.js Documentation

The ngResource module provides interaction support with RESTful services via the $resource service.

View

@Scripts.Render("~/Scripts/angular.js")
@Scripts.Render("~/Scripts/angular-route.js")
@Scripts.Render("~/Scripts/angular-resource.js")
@Scripts.Render("~/Scripts/app.js")

You also need to fix your module declaration to include ngResource:

var app = angular.module("app", ['ngRoute','ngResource']);

When i am trying to get data to use in Angular, i have a WEB API service as the data provider. Then i do a get call in my angular controller.

For instance, in your case instead of returning data in your ActionResult, have a webapi controller:

public HttpResponseMessage Get()
{
    using(MoviesEntities db = new MoviesEntities())
    {
        var result = db.Users.OrderBy(x => x.name).Select(x=>new{x.name,x.summoner}).ToList();
        HttpResponseMessage msg = new HttpResponseMessage();
        msg.Content = new ObjectContent<object>(result, new System.Net.Http.Formatting.JsonMediaTypeFormatter());



        msg.StatusCode = HttpStatusCode.OK;
        return msg;
    }
}

Then in your Angular Controller call that service and fill your $scope:

app.controller('AccountController', function ($scope, userService, $resource, $http) {
    $scope.getUsers = function () {
        $http({
            url: '/api/APITest',
            method: "GET"
        })
        .then(function (result) {
            $scope.userList = angular.copy(result.data);
        })
    }
    getUsers();
});

Your View also needs some change. Use userList instead of Model. Probably you would like to rename actors to actor or even user as it would make more sence:

<table class="table table-striped">
    <tr ng-repeat="actors in userList">
        <td>{{actors.name}}</td>
        <td>{{actors.summoner}}</td>
    </tr>
</table>

A piece of advise: Create an _AngularLayout and add the script declaration there. Then use this for your angular enabled views. That way you do not have to define them in each of your views.

Sign up to request clarification or add additional context in comments.

6 Comments

ah yes yes, but it still does not work haha. I think I need to do something with my Controllers..
Then try F12 on your browser and see what the error is.
updated thread for cleaner view. Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:modulerr] Failed to instantiate module ngRoute due to: Error: [$injector:nomod] Module 'ngRoute' is not available! You either misspelled the module name...<omitted>...2)
You also need : angular-resource.js ;-)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.