Folder Structure
Untuk menginstall angular JS pada ASP.NET, buka Package Manager Console, kemudian ketik
Install-Package AngularJS.Core
Install-Package AngularJS.Route
Scripts/app/app.js
[code lang=”js”]
var app = angular.module(‘intraApp’, [‘kendo.directives’, ‘ngRoute’, ‘ngAnimate’, ‘IntraService’])
.config(function ($routeProvider) {
$routeProvider
.when(‘/’, {
templateUrl: ‘/Intra/Intra’,
controller: ‘intraController’
})
.when(‘/create’,
{
templateUrl: ‘/Intra/Create’,
controller: ‘intraController’
})
.when(‘/edit/:id’,
{
templateUrl: ‘/Intra/Create’,
controller: ‘intraController’
})
.otherwise(
{
redirectTo: ‘/’
});
});
app.directive(‘homeButton’, function(){
return {
restrict: ‘E’,
template: ‘<div class="col-xs-3">’ +
‘<a href="{{ intra.link }}" class="btn btn-primary col-xs-12"><span class="glyphicon {{ intra.icon == null || intra.icon == \’\’ ? \’glyphicon-comment\’ : intra.icon }}"></span> {{ intra.name }}</a>’ +
‘</div>’,
};
});
[/code]
Scripts/app/controllers/intraController.js
[code lang=”js”]
‘use strict’;
app.controller(‘intraController’,
function ($scope, $rootScope, $location, $routeParams, $route, intraDataSource, intraService)
{
var intraId = $routeParams.id; // jika edit, maka diperoleh id
$scope.intra = {
id: 0,
name: "",
link: "",
icon: ""
}; // model untuk create dan edit
$scope.errors = null; // error message untuk create dan edit
$scope.message = $rootScope.message; // message ketika berhasil create, edit, ataupun delete
//fungsi untuk create new item pada halaman index
$scope.addItem = function () {
$location.url(‘/create’); // mengarahkan ke halaman create
}
//fungsi edit pada masing-masing item dalam kendo grid
$scope.editItem = function (id) {
$location.url(‘/edit/’ + id); // mengarahkan ke halaman edit
}
//fungsi delete pada masing-masing item dalam kendo grid
$scope.deleteItem = function (id) {
var r = confirm(‘Are you sure want to delete this entry?’);
if (r) {
intraService.delete(id)
.success(function (data) {
if (data.status == 200) {
$rootScope.message = data.message;
$route.reload();
} else {
$scope.errors = data.data;
}
})
.error(function (data) {
$scope.errors[0] = data;
});
}
}
// option untuk kendo
$scope.mainGridOptions = {
dataSource: intraDataSource,
filterable: kendoGridFilterable,
pageable: true,
sortable: true,
height: 400,
columns: [
{
field: "name",
},
{
field: "link",
template: ‘<a href="#= link #">#= link #</a>’
},
{
field: "icon",
},
{
template: ‘<a class="k-button-icon" href="javascript:" ng-click="editItem(#= id #)"><span class="glyphicon glyphicon-edit"></span></a>’ +
‘<a class="k-button-icon" href="javascript:" ng-click="deleteItem(#= id #)"><span class="glyphicon glyphicon-remove"></span></a>’,
width: "85px"
}
]
};
/*create and edit page */
$scope.modifiedTitle = "Add New Intra Application";
if (intraId != null) {
intraService.get(intraId).success(function (data) {
$scope.intra = data
$scope.modifiedTitle = $scope.intra.name + " | Edit";
});
}
// fungsi save pada halaman create atau edit
$scope.save = function () {
console.log(intraService);
if ($scope.intra.id == 0) {
intraService.create($scope.intra)
.success(function (data) {
if (data.status == 200) {
$rootScope.message = data.message;
$location.url(‘/’);
} else {
$scope.errors = data.data;
}
})
.error(function (data) {
$scope.errors[0] = data;
});
} else {
intraService.edit($scope.intra)
.success(function (data) {
if (data.status == 200) {
$rootScope.message = data.message;
$location.url(‘/’);
} else {
$scope.errors = data.data;
}
})
.error(function (data) {
$scope.errors[0] = data;
});
}
};
// membatalkan create / edit
$scope.cancel = function () {
$location.url(‘/’);
}
});
[/code]
Scripts/app/controllers/homeController.js
[code lang=”js”]
‘use strict’;
app.controller(‘homeController’,
function ($scope, $rootScope, intraService) {
intraService.all().success(function (data) {
$scope.intras = data.data;
});
}
);
[/code]
Scripts/app/services/intraDataSource.js
[code lang=”js”]
‘use strict’;
app.factory(‘intraDataSource’,
function (intraModel) {
var crudServiceBaseUrl = "/api/intra";
return new kendo.data.DataSource({
type: "json",
transport: {
read: {
async: false,
url: crudServiceBaseUrl,
dataType: "json"
}
},
batch: false,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
schema: {
data: function (data) { return data.data; },
total: function (data) { return data.total; },
model: intraModel
},
error: function (e) {
alert(e.xhr.responseText);
}
});
});
[/code]
Scripts/app/services/intraModel.js
[code lang=”js”]
‘use strict’;
app.factory(‘intraModel’, function () {
return kendo.data.Model.define({
id: "id",
fields: {
id: { editable: false, nullable: false },
name: { title: "Name", type: "string" },
link: { title: "Link URL", type: "string" },
icon: { title: "Icon Class", type: "string" },
}
});
});
[/code]
Scripts/app/services/intraService.js
[code lang=”js”]
‘use strict’;
app.factory(‘intraService’, [‘$http’, function ($http) {
var urlBase = ‘http://localhost:11111/api/intra’;
var intraService = {};
intraService.create = function (intra) {
return $http.post(urlBase, intra);
};
intraService.all = function () {
return $http.get(urlBase);
};
intraService.get = function (id) {
return $http.get(urlBase + ‘/’ + id);
};
intraService.edit = function (intra) {
return $http.put(urlBase, intra);
};
intraService.delete = function (id) {
return $http.delete(urlBase + ‘/’ + id);
};
return intraService;
}]);
[/code]
Controllers/Service/IntraController.cs (API)
[code lang=”csharp”]
using Business.Abstract;
using Business.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;
using WebUI.Infrastructure;
using WebUI.Models.Intra;
using WebUI.Models.Service;
namespace WebUI.Controllers.Service
{
public class IntraController : ApiController
{
private IIntraApplicationRepository IntraRepo;
public IntraController(IIntraApplicationRepository repoIntra)
{
IntraRepo = repoIntra;
}
// GET api/intra
public KendoGridResponseStub<IntraPresentationStub> Get()
{
GridRequestParameters param = GridRequestParameters.Current;
List<intra_applications> items = IntraRepo.Find(param.Skip, param.Take, (param.Sortings != null ? param.Sortings.ToList() : null), (param.Filters != null ? param.Filters : null));
int total = IntraRepo.Count(param.Filters);
KendoGridResponseStub<IntraPresentationStub> result = new KendoGridResponseStub<IntraPresentationStub>();
result.total = total;
result.data = new IntraPresentationStub().MapList(items);
return result;
}
// GET api/intra/5
public intra_applications Get(int id)
{
return IntraRepo.FindByPk(id);
}
// POST api/intra
public ServiceResponseStub<string> Post([FromBody]IntraFormStub model)
{
ServiceResponseStub<string> response = new ServiceResponseStub<string>();
if (!ModelState.IsValid)
{
response.status = 404;
response.message = "Some Fields cannot be empty.";
response.data = new List<string>();
var allErrors = ModelState.Values.SelectMany(v => v.Errors);
response.data.AddRange(allErrors.Select(p => p.ErrorMessage));
return response;
}
try
{
IntraRepo.Save(model.GetDbData());
}
catch (Exception)
{
response.status = 500;
response.message = "Oops… Somethings gone wrong.";
return response;
}
response.status = 200;
response.message = String.Format(HttpContext.GetGlobalResourceObject("MyGlobalMessage", "CreateSuccess").ToString(), model.Name);
return response;
}
// PUT api/intra/5
public ServiceResponseStub<string> Put([FromBody]IntraFormStub model)
{
ServiceResponseStub<string> response = new ServiceResponseStub<string>();
if (!ModelState.IsValid)
{
response.status = 404;
response.message = "Some Fields cannot be empty.";
response.data = new List<string>();
var allErrors = ModelState.Values.SelectMany(v => v.Errors);
response.data.AddRange(allErrors.Select(p => p.ErrorMessage));
return response;
}
try
{
IntraRepo.Save(model.GetDbData());
}
catch (Exception)
{
response.status = 500;
response.message = "Oops… Somethings gone wrong.";
return response;
}
response.status = 200;
response.message = String.Format(HttpContext.GetGlobalResourceObject("MyGlobalMessage", "EditSuccess").ToString(), model.Name);
return response;
}
// DELETE api/intra/5
public ServiceResponseStub<string> Delete(int id)
{
ServiceResponseStub<string> response = new ServiceResponseStub<string>();
intra_applications intraApps = IntraRepo.FindByPk(id);
IntraRepo.Delete(intraApps);
response.status = 200;
response.message = intraApps.name + " berhasil dihapus.";
return response;
}
}
}
[/code]
Controllers/IntraController.cs (MVC Page)
[code lang=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Business.Abstract;
using WebUI.Extension;
using WebUI.Models.Intra;
using Business.Entities;
using WebUI.Models;
using WebUI.Infrastructure;
using System.Web.Script.Serialization;
namespace WebUI.Controllers
{
public class IntraController : MyController
{
public IntraController(ILogRepository repoLog)
: base(repoLog)
{
}
public ActionResult Index()
{
return View();
}
public ActionResult Intra()
{
return PartialView();
}
public ActionResult Create()
{
IntraFormStub model = new IntraFormStub();
return PartialView("Form", model);
}
}
}
[/code]
Views/Home/Index.cshtml
[code lang=”html”]
<div ng-app="intraApp" ng-controller="homeController">
<div class="page-header">
<h1>@ViewBag.Title</h1>
</div>
<div class="row">
<home-button ng-repeat="intra in intras"></home-button>
</div>
</div>
[/code]
Views/Intra/Index.cshtml
[code lang=”html”]
@{
ViewBag.Title = "Intranet Application";
ViewBag.Description = "Intranet Application";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-app="intraApp">
<div ng-view></div>
</div>
[/code]
Views/Intra/Intra.cshtml
[code lang=”html”]
@{
ViewBag.Title = "Index";
}
<div class="page-header">
<div class="btn-group pull-right">
<button class="btn btn-default" ng-click="addItem()">Add Intra Application</button>
</div>
<h1>@ViewBag.Title</h1>
</div>
<div class="alert alert-success" role="alert" ng-show="message">
{{message}}
</div>
<kendo-grid options="mainGridOptions"></kendo-grid>
[/code]
Views/Intra/Form.cshtml
[code lang=”html”]
@model WebUI.Models.Intra.IntraFormStub
@{
string currentController = (string)ViewContext.RouteData.Values["controller"];
string currentAction = (string)ViewContext.RouteData.Values["action"];
string backLink = "";
}
<div class="page-header">
<h1>{{ modifiedTitle }}</h1>
</div>
@using (@Html.BeginForm(currentAction, currentController, FormMethod.Post, new { @class = "form-horizontal" }))
{
<div class="alert alert-danger" role="alert" ng-show="errors">
<ul>
<li ng-repeat="error in errors">{{ error }}</li>
</ul>
</div>
@Html.HiddenFor(model => model.Id, new { ng_model="intra.id" })
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "col-xs-2 control-label" })
<div class="col-xs-4">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", ng_model = "intra.name" } })
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Link, new { @class = "col-xs-2 control-label" })
<div class="col-xs-4">
@Html.EditorFor(model => model.Link, new { htmlAttributes = new { @class = "form-control", ng_model = "intra.link" } })
@Html.ValidationMessageFor(model => model.Link)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Icon, new { @class = "col-xs-2 control-label" })
<div class="col-xs-4">
@Html.EditorFor(model => model.Icon, new { htmlAttributes = new { @class = "form-control", ng_model = "intra.icon" } })
@Html.ValidationMessageFor(model => model.Icon)
<p class="help-block">Choose Icon class from glyphicon provided by Bootstrap.</p>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<button type="button" class="btn btn-primary" ng-click="save()">Save</button>
<button type="button" class="btn btn-link" ng-click="cancel()">Cancel</button>
</div>
</div>
}
[/code]
App_Start/BundleConfig.cs
[code lang=”csharp”]
…
bundles.Add(new ScriptBundle("~/bundles/angular").Include(
"~/Scripts/angular.js",
"~/Scripts/angular-route.js"));
bundles.Add(new ScriptBundle("~/bundles/app").Include(
"~/Scripts/app/app.js",
"~/Scripts/app/services/intraModel.js",
"~/Scripts/app/services/intraDataSource.js",
"~/Scripts/app/services/intraService.js",
"~/Scripts/app/controllers/intraController.js",
"~/Scripts/app/controllers/homeController.js"));
…
BundleTable.EnableOptimizations = false;
[/code]
Views/Shared/_Layout.cshtml
[code lang=”html”]
<body>
…
@Scripts.Render("~/bundles/angular")
@Scripts.Render("~/bundles/app")
@Scripts.Render("~/bundles/kendo")
…
</body>
[/code]
