AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Wednesday, 5 July 2017

How to create a single page application using AngularJS, WebAPI & MVC?

In this article I am going discuss How to create a single page application using AngularJS, Web-API and MVC with a basic example for beginners. How to implement routing, controllers and services using angular. Please  follow the below steps for creating the Angular application.
Step 1- Add New Project

Step 2-Select Empty Template with MVC & Web API
Step 4- Go to menu Tools> Nuget package Manager and install the AngularJS and AngularJS.Route



Step-5 Create one HomeController with following code.

 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        
        public ActionResult Page1()
        {
            return PartialView("Page1");
        }

        
        public ActionResult Page2()
        {
            return PartialView("Page2");
        }

        
        public ActionResult Page3()
        {
            return PartialView("Page3");
        }

    }

Step-6 Create an HomeAPIController with following code.


 public class HomeAPIController : ApiController
    {  
        public IHttpActionResult Get(string content)
        {
            return new JsonResult<string>(content, new JsonSerializerSettings(), Encoding.UTF8, this);
        }
    }


Step-7 Create a new folder App inside the solution.


Step-8 Create an module.js file inside the App directory with following code.

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

//Showing Routing
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    debugger;
    $routeProvider.when('/page1',
        {
            templateUrl: 'Home/Page1',
            controller: 'Page1Controller'            
        });
    $routeProvider.when('/page2',
        {
            templateUrl: 'Home/Page2',
            controller: 'Page2Controller'
        });
    $routeProvider.when('/page3',
        {
            templateUrl: 'Home/Page3',
            controller: 'Page3Controller'
        });
    $routeProvider.otherwise(
        {
            redirectTo: '/'
        });

    $locationProvider.html5Mode({ enabled: true, requireBase: false });
}]);  

Step-7 Add Controllers and Services folder inside of it add file homeController.js and homeService.js with the following code.

homeController.js


app.controller("Page1Controller", function ($scope, $location, HomeService) {
    getContent();

 function getContent() {
  debugger;
        var promiseobj = HomeService.GetDataPage1();

        promiseobj.then(function (pl) {
            $scope.content = pl.data;
        },
            function (errorPl) {
                $scope.error = 'failure loading', errorPl;
            });
    }
});  

app.controller("Page2Controller", function ($scope, $location, HomeService) {
    getContent();

    function getContent() {
        var promiseobj = HomeService.GetDataPage2();

        promiseobj.then(function (pl) {
            $scope.content = pl.data;
        },
            function (errorPl) {
                $scope.error = 'failure loading', errorPl;
            });
    }
});

app.controller("Page3Controller", function ($scope, $location, HomeService) {
    getContent();

    function getContent() {
        var promiseobj = HomeService.GetDataPage3();

        promiseobj.then(function (pl) {
            $scope.content = pl.data;
        },
            function (errorPl) {
                $scope.error = 'failure loading', errorPl;
            });
    }
});

homeService.js


app.service("HomeService", function ($http) {
  
 this.GetDataPage1 = function () {
  debugger;
        return $http.get("/api/HomeAPI?content=Page1");
    };

    this.GetDataPage2 = function () {
  return $http.get("/api/HomeAPI?content=Page2");
    };

    this.GetDataPage3 = function () {
  return $http.get("/api/HomeAPI?content=Page3");
    };
});  

Step-8 Add the following views
  • _Layout.cshtml - Layout file for the template.
  • Index.cshtml - First page that render the data.
  • Page1.cshtml - Partial view for page 1
  • Page2.cshtml - Partial view for page 2
  • Page3.cshtml - Partial view for page 3
_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body data-ng-app="ApplicationModule">
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Angular POC", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

Index.cshtml
@{
    ViewBag.Title = "Index";
}

<a href="page1" class="navbar-brand">Page 1</a>
<a href="page2" class="navbar-brand">Page 2</a>
<a href="page3" class="navbar-brand">Page 3</a>
<br />
<div class="col-sm-12">
    <div data-ng-view></div>
</div>
@section scripts {

    <script type="text/javascript" src="@Url.Content("~/Scripts/angular.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/angular-route.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/App/module.js")"></script>
    <script src="@Url.Content("~/App/Services/homeService.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/App/Controllers/homeController.js")" type="text/javascript"></script>

}

Page1.cshtml
<div class="col-sm-12">
 <h2>{{content}}</h2>
</div>

Page2.cshtml
<div class="col-sm-12">
 <h2>{{content}}</h2>
</div>

Page3.cshtml
<div class="col-sm-12">
 <h2>{{content}}</h2>
</div>

Download the Source Code - Link

0 comments :

Post a comment

  • Popular Posts
  • Comments