Thursday, November 8, 2018

Simple AngularJS application with ASP.NET MVC

In this example i'm gonna show you how to return a simple data set in from ASP.NET MVC server side and bind the view using Angular directives.

First, let see how our controller looks like on the server side.

public class StudentController : Controller
{
    // GET: Student
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetAllStudents()
    {
        return Json(GetStudents(), JsonRequestBehavior.AllowGet);
    }

    private List<Student> GetStudents()
    {
        List<Student> students = new List<Student>()
        {
            new Student()
            {
                Name = "Chamara",
                School = "Melbourne"
            },
            new Student()
            {
                Name = "Layana",
                School = "Bayswater"
            }
        };

        return students;
    }
}

public class Student
{
    public string Name { get; set; }
    public string School { get; set; }
}

Then the Student.js file which holds the Angular js code.

var StudentApp = angular.module('StudentApp', []);


StudentApp.factory("StudentService", ['$http', function ($http) {

    var StudentService = {};
    StudentService.getStudents = function () {

        return $http.get("/Student/GetAllStudents");

    };

    return StudentService;

}]);

StudentApp.controller("StudentController", function ($scope, StudentService) {

    getStudents();
    function getStudents() {

        StudentService.getStudents().then(function (studs) {

            $scope.students = studs;
            console.log($scope.students);

        });

    }

});
Finally, binding the view.

<script src="~/Scripts/app/StudentApp.js"></script>

<h2>Students</h2>

<div ng-app="StudentApp">
    <div ng-controller="StudentController">       
        <table>
            <tr ng-repeat="r in students.data">
                <td>{{r.Name}}</td>
                <td>{{r.School}}</td>
            </tr>
        </table>
    </div>
</div>