Angular js with ASP.NET MVC is more popular now days and for beginners, I will tell you what is angular js and show you a practical example of ASP.NET MVC for inserting, deleting and displaying data using angular js.
Basically, this article will demonstrate with example the
following:
- Step by
step procedure to create asp.net MVC project with angular js
- How to install
angular js package in ASP.NET MVC project
- How to
create module, service and controller in angular js
- How to get
data from server side(C#)
- How to
bind/Load/Fill data from Server side to html page using angular js
- How to
perform insert, edit, update and delete operation on view using angular js data binding
What you need
As all of you have visual studio 2012 so that I am using
visual studio 2012 with Asp.net MVC 4.
Let's get started
Ok, first of all, you have to create a new MVC
project by selecting New Project in Visual Studio 2012... on
the start screen, then drill down to Templates
=> Visual C# => Web => ASP.NET MVC 4 Web Application and
can name it as you prefer.
Select basic Asp.net MVC 4 project template
Include Angular in our project via Nuget packages, you can
also download it from angular website. We have to install angular js package to
our project for this please does below steps
Open the Package manager Console from View =>
Other Windows => Package Manager Console as shown below:
1.
Install Angular js package by using below
command
2.
As Angular js Route package is not come with
angular js we have to install separate package for angular js route. so please Install
Angular js package by using below command
Step 1 : Create Model in MVC project
As all of you knows that in MVC we have model for database
record we will create first Model using entity framework
Create Employee table with this schema. ID is primary key
and it is Identity
Add new Entity Data Model using Entity framework in Models
folder
Select Database name from dropdown
We have
Step 2 : Create Controller in MVC
project
Add new controller named as HomeController
Add below methods to HomeController
public ActionResult Index()
{
return View();
}
public JsonResult getAll()
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
var employeeList = dataContext.Employees.ToList();
return Json(employeeList, JsonRequestBehavior.AllowGet);
}
}
public JsonResult getEmployeeByNo(string EmpNo)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
int no = Convert.ToInt32(EmpNo);
var employeeList = dataContext.Employees.Find(no);
return Json(employeeList, JsonRequestBehavior.AllowGet);
}
}
public string UpdateEmployee(Employee Emp)
{
if (Emp != null)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
int no = Convert.ToInt32(Emp.Id);
var employeeList =
dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
employeeList.name =
Emp.name;
employeeList.mobil_no =
Emp.mobil_no;
employeeList.email =
Emp.email;
dataContext.SaveChanges();
return "Employee Updated";
}
}
else
{
return "Invalid
Employee";
}
}
public string AddEmployee(Employee Emp)
{
if (Emp != null)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
dataContext.Employees.Add(Emp);
dataContext.SaveChanges();
return "Employee Updated";
}
}
else
{
return "Invalid
Employee";
}
}
public string DeleteEmployee(Employee Emp)
{
if (Emp != null)
{
using (SampleDBEntities dataContext = new SampleDBEntities())
{
int no = Convert.ToInt32(Emp.Id);
var employeeList =
dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
dataContext.Employees.Remove(employeeList);
dataContext.SaveChanges();
return "Employee Deleted";
}
}
else
{
return "Invalid
Employee";
}
}
In the above method
1. 1. getAll()
Method will return all the emloyees in json format
2. getEmployeeByNo() Method will return employee details by employee number
3. UpdateEmployee() method will update existing employee details
4. AddEmployee() method will add new employee to database
5. DeleteEmployee() method will delete existing employee
2. getEmployeeByNo() Method will return employee details by employee number
3. UpdateEmployee() method will update existing employee details
4. AddEmployee() method will add new employee to database
5. DeleteEmployee() method will delete existing employee
Right
click on Index() and click add View . so
index.cshtml automatically will be created
Now design a table to accept inputs from user in CRUD page. Add
below html to index.cshtml
In angular js we have used following directives
1. ng-Click : The ngClick directive allows you to specify custom behavior when an element is clicked.
2. ng-controller: The ngController directive attaches a controller class to the view
3. ng-Repeat : The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.
4. ng-model : ngModel is responsible for Binding the view into the model, which other directives such as input, textarea or select require.
<div ng-controller="myCntrl">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<h1> Employee Details Page</h1>
<br />
<input type="button" class="btnAdd" value=" Add Employee" ng-click="AddEmployeeDiv()" />
<div class="divList">
<p class="divHead">Employee List</p>
<table cellpadding="12" class="table table-bordered table-hover">
<tr>
<td><b>ID</b></td>
<td><b>Name</b></td>
<td><b>Email</b></td>
<td><b>Age</b></td>
<td><b>Actions</b></td>
</tr>
<tr ng-repeat="employee in
employees">
<td>
{{employee.Id}}
</td>
<td>
{{employee.name}}
</td>
<td>
{{employee.email}}
</td>
<td>
{{employee.Age}}
</td>
<td>
<span ng-click="editEmployee(employee)" class="btnAdd">Edit</span>
<span ng-click="deleteEmployee(employee)" class="btnRed">Delete</span>
</td>
</tr>
</table>
</div>
<div ng-show="divEmployee">
<p class="divHead">{{Action}} Employee</p>
<table>
<tr>
<td><b>Id</b></td>
<td>
<input type="text" disabled="disabled" ng-model="employeeId" />
</td>
</tr>
<tr>
<td><b>Name</b></td>
<td>
<input type="text" ng-model="employeeName" />
</td>
</tr>
<tr>
<td><b>Email</b></td>
<td>
<input type="text" ng-model="employeeEmail" />
</td>
</tr>
<tr>
<td><b>Age</b></td>
<td>
<input type="text" ng-model="employeeAge" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" class="btnAdd" value="Save" ng-click="AddUpdateEmployee()" />
</td>
</tr>
</table>
</div>
</div>
STEP 3: Writing Angular js MVC code
So We are ready with our Model View and Controller now we
have to write angular js code
Create three JavaScript files as shown in below
1.
Controller.js
2.
Module.js
3.
Service.js
1.
Module .js
angular.module
is used to configure the $injector. The module is a container for the
different parts of an application
2.
Service.js
Service .js file is used for calling server side code by using $http. In
Service.js file we have created an angular js service called as myService. To
call MVC HomeControllers insert update,delete function we have created 3
functions in service.js
app.service("myService", function ($http) {
//get
All Eployee
this.getEmployees = function () {
debugger;
return $http.get("Home/GetAll");
};
// get
Employee By Id
this.getEmployee = function (employeeID) {
var response = $http({
method: "post",
url: "Home/getEmployeeByNo",
params: {
id: JSON.stringify(employeeID)
}
});
return response;
}
//
Update Employee
this.updateEmp = function (employee) {
var response = $http({
method: "post",
url: "Home/UpdateEmployee",
data: JSON.stringify(employee),
dataType: "json"
});
return response;
}
// Add
Employee
this.AddEmp = function (employee) {
var response = $http({
method: "post",
url: "Home/AddEmployee",
data: JSON.stringify(employee),
dataType: "json"
});
return response;
}
//Delete
Employee
this.DeleteEmp = function (employeeId) {
var response = $http({
method: "post",
url: "Home/DeleteEmployee",
params: {
employeeId: JSON.stringify(employeeId)
}
});
return response;
}
});
3.
Controller.js
In controller.js we have created new controller named myCntrl. In controller we are
calling method of myService in controller.js
app.controller("myCntrl", function ($scope, myService)
{
$scope.divEmployee = false;
GetAllEmployee();
//To Get
All Records
function GetAllEmployee() {
debugger;
var getData = myService.getEmployees();
debugger;
getData.then(function (emp) {
$scope.employees = emp.data;
},function () {
alert('Error in getting records');
});
}
$scope.editEmployee = function (employee) {
debugger;
var getData = myService.getEmployee(employee.Id);
getData.then(function (emp) {
$scope.employee = emp.data;
$scope.employeeId = employee.Id;
$scope.employeeName =
employee.name;
$scope.employeeEmail = employee.email;
$scope.employeeAge = employee.Age;
$scope.Action = "Update";
$scope.divEmployee = true;
},
function () {
alert('Error in getting records');
});
}
$scope.AddUpdateEmployee = function ()
{
debugger;
var Employee = {
Name: $scope.employeeName,
Email: $scope.employeeEmail,
Age: $scope.employeeAge
};
var getAction = $scope.Action;
if (getAction == "Update") {
Employee.Id = $scope.employeeId;
var getData = myService.updateEmp(Employee);
getData.then(function (msg) {
GetAllEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in updating record');
});
} else {
var getData = myService.AddEmp(Employee);
getData.then(function (msg) {
GetAllEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in adding record');
});
}
}
$scope.AddEmployeeDiv=function()
{
ClearFields();
$scope.Action = "Add";
$scope.divEmployee = true;
}
$scope.deleteEmployee = function (employee)
{
var getData = myService.DeleteEmp(employee.Id);
getData.then(function (msg) {
GetAllEmployee();
alert('Employee Deleted');
},function(){
alert('Error in Deleting Record');
});
}
function ClearFields() {
$scope.employeeId = "";
$scope.employeeName = "";
$scope.employeeEmail = "";
$scope.employeeAge = "";
}
});
STEP 4 : Call Angular js
In the final we have to call angular js .We are calling
angular js in layout.cshtml page
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Content/Angular/Module.js"></script>
<script src="~/Content/Angular/Service.js"></script>
<script src="~/Content/Angular/Controller.js"></script>
@Styles.Render("~/Content/css")
<style>
</style>
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
By using this, you have successfully inserted data in the
database and you have also shown this in the gridview. Click on Add Employee
Happy Programming!!
Don’t forget to leave your feedback and comments below!
Sujeet Bhujbal
--------------------------------------------------------------------------------
Blog: www.sujitbhujbal.com
Personal Website :-http://sujitbhujbal.wordpress.com/
Facebook :-http://www.facebook.com/bhujbal.sujit
CodeProject:-http://www.codeproject.com/Members/Sujit-Bhujbal
Linkedin :-http://in.linkedin.com/in/sujitbhujbal
Stack-Exchange: http://stackexchange.com/users/469811/sujit-bhujbal
Twitter :-http://twitter.com/SujeetBhujbal
JavaTalks :-http://www.javatalks.com/Blogger/sujit9923/
--------------------------------------------------------------------------------