Introduction
As I have seen many people searching for Angular code in ASP.NET MVC, binding via Angular, routeProvider
, then CRUD. So I have created a demo application which would meet your requirements. For table basic design, I had used bootstrap.
Create, Read, Update, Delete records of records to edit.
Create Employee
table with this schema.
Using the Code
First, we need to create a project in ASP.MVC 4 and name it as you prefer.
So in MVC, we have Model for Database Records, Views for Visual Representation of records and Controller that handles the input from user.
In the next step, we will select basic project Template.
So we will create one Index view. Next, create a Home controller and assign it with our Index view.
Include Angular in our project via Nuget packages, you can also download it from Angular website. So here, we will add Angular in BundleConfig
(Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets) so that when we include it in layout page, we will be able to use Angular in partial views, so in this manner, we don't need to include Angular in each view.
Go in Appstart
->BundleConfig.cs
bundles.Add(new Bundle("~/bundles/scripts")
.Include("~/Scripts/angular.js")
.Include("~/Scripts/jquery-{version}.js"));
Give reference of this bundle in Layout page.
@Scripts.Render("~/bundles/scripts")
Create a Partial View (a partial view enables you to define a view that will be rendered inside a parent view). Name it as CRUD Page. Include it in our HomeController
.
Create a routeConfig.js file in Scripts folder for Angular routes. First thing to keep in mind is that here, we are going to mixup the Routing of ASP.NET MVC structure and Angular routing structure. ASP.NET MVC routing is a server side routing and Angular routing is a client side routing. So here, we do need to configure Angular routing in routeConfig.cs file to register Angular routes.
Go in Appstart
-> RouteConfig.cs.
routes.MapRoute(
name: "routes",
url: "{route}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { route = @"^(login)$" }
);
In Name
parameter we specify route name. In url
parameter, we specify how routes are configured (first is route name, second is to specify any arguments send via $routeParams
- This service of Angular allows us to retrieve current set of route parameters).
Create loginController.js file in Scripts folder, write this code:
angular
.module('MyApp.ctrl.crud', [])
.controller('loginController',[
'$scope',
function ($scope) {
alert("In Login Controller")
}
]);
Write this code in Angular routeConfig.js file:
angular
.module('MyApp', [
'ngRoute',
'MyApp.ctrl.crud',
])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: '/Home/CRUD',
controller: 'loginController'
});
$routeProvider.when('/login', {
templateUrl: '/Home/loginPage',
controller: 'crudController'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
Note: From Angular version 1.2, ngRoute is now a separate module in angular-route.js, so if you are using Angular from version 1.2, you need to download a separate angular route file and do remember to include it as dependency as second argument in your module. Here, we have included 'ngRoute
' as dependency.
routeprovider
provides two methods:
routeProvider.when
:
templateUrl
: gives the virtual path of our view controller
: gives the route to our view (controller)
routeProvider.otherwise
: Sets route definition that will be used on route change when no other route definition is matched
To improve the organization of our app, we keep views and controllers in separate folders and routeProvider
helps to associate that for which view, which controller has to be assigned. That's not all we need to do to use the codes of the controller. We also have to add the modules as dependencies. So we have included our login module in routeConfig
as dependency in the second argument.
Note: Enabling html5Mode
allows you to use natural URLs that look like:
Instead of unnatural hashbang URLs that look like:
- http://Angular.com/#!/login
Using html5mode
is compatible with any browser that supports the HTML5 History API (IE10+ and every other browser).
Note: We are using Partial views to be rendered in our Main view so do remember to include the following code in index.cshtml.
<div ng-view></div>
so that our partial view will be rendered in this DIV
tag.
Load the routeConfig file and loginCtrl file in Index.cshtml page.
So till here, we have configured our application for angular routes in ASP.NET MVC. Let's test our application. Click on Run.
So till here, we have configured our app to provide routes in ASP.NET MVC.
Now design a table to accept inputs from user in CRUD page.
<div style="text-align:center">CRUD </div>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<table class="table" style="width:400px">
<tbody>
<tr>
<td>Employee ID</td>
<td><input type="text" data-ng-model="emp.id" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" data-ng-model="emp.name" /></td>
</tr>
<tr>
<td>Designation</td>
<td><input type="text" data-ng-model="emp.designation" /></td>
</tr>
<tr>
<td>Mobile No</td>
<td><input type="text" data-ng-model="emp.mobile" /></td>
</tr>
<tr>
<td><input type="button" data-ng-click="clear()" value="Clear" /></td>
<td><input type="button" data-ng-click="save()" value="Save" /></td>
</tr>
</tbody>
</table>
<br />
This table is used to take inputs from user.
Write this code in Angular controller.
angular
.module('MyApp.ctrl.crud', [])
.controller('loginController',[
'$scope',
function ($scope) {
$scope.emplist = [];
$scope.load = function () {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: '/Home/getList',
success: function (data) {
$scope.emplist = data;
$scope.$apply();
console.log($scope.emplist);
}
});
}
$scope.load();
$scope.emp = {
id: '',
name: '',
designation: '',
mobile: ''
}
$scope.clear = function () {
$scope.emp.id = '';
$scope.emp.name = '';
$scope.emp.designation = '';
$scope.emp.mobile = '';
}
$scope.save = function () {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($scope.emp),
url: '/Home/save',
success: function (data, status) {
$scope.clear();
},
error: function (status) { }
});
};
}
]);
Here, we have created an emp
model which we use to take inputs from user. For calling our controller in MVC, we are using Ajax calls. First, we will take inputs from user.
First, Save Records
In save
function, we are making an Ajax call and sending emp
model to Home
controller in ASP MVC.
Now to fetch data from Ajax in our home controller, we do need to create Employee
model to temp save our data. It's best practise to keep models in Model folder. Create Employee
class in Model folder in ASP MVC.
public class Employee
{
public int id { get; set; }
public string name { get; set; }
public string designation { get; set; }
public Int64 mobile { get; set; }
}
Now, we will create a Repository
class in Model folder to interact with our database to save, update, delete our records.
public class repository
{
SqlConnection con = new SqlConnection("Data Source=172.168.1.95,62502;
Initial Catalog = CRUD; User ID = sa; Password = winworld@1");
public void save(Employee data){
con.Open();
string save = "insert into emp values(@id, @name, @desg, @mob)";
SqlCommand cmd = new SqlCommand(save, con);
cmd.Parameters.AddWithValue("@id", data.id);
cmd.Parameters.AddWithValue("@name", data.name);
cmd.Parameters.AddWithValue("@desg", data.designation);
cmd.Parameters.AddWithValue("@mob", data.mobile);
cmd.ExecuteNonQuery();
con.Close();
}
After this, we will call save
method of repository
class in our Home
controller. We are using JsonResult
class to fetch data from CRUD page.
public JsonResult save(Employee data)
{
repository save = new repository();
save.save(data);
return null;
}
Create an object of repository
class, call save
method, then pass the model fetched from Json in parameter of Employee
class object (data
).
Now, let's check if our data is saved in database or not.
So our data is saved in database.
Next, Retrieve Data From Database
So to list our records on CRUD page, we will create another table. Write this code in CRUD page.
<div style="text-align:center; width:400px">
<table class="table table-striped" >
<thead>
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Designation</th>
<th>Mobile No</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item in emplist">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.designation}}</td>
<td>{{item.mobile}}</td>
<td><input type="button"
data-ng-click="delete(item)" value="Delete"/></td>
</tr>
</tbody>
</table>
</div>
To display the records fetched from our database and show it to the user, we will use ng-repeat
tag that will iterate through each record. Write this code in Angular controller.
$scope.emplist = [];
$scope.load = function () {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: '/Home/getList',
success: function (data) {
$scope.emplist = data;
$scope.$apply();
console.log($scope.emplist);
}
});
}
$scope.load();
So here, we are calling getList
method created in ASP MVC Home controller via Ajax call and after successful data retrieval, we are assigning it to emplist
array.
Write this code in Repository
class:
public List<Employee> getList()
{
con.Open();
var emp = new List<Employee>();
string get = "select * from emp";
SqlCommand cmd = new SqlCommand(get, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee e = new Employee();
e.id = Convert.ToInt32(dr[0]);
e.name = Convert.ToString(dr[1]);
e.designation = Convert.ToString(dr[2]);
e.mobile = Convert.ToInt64(dr[3]);
emp.Add(e);
}
con.Close();
return emp;
}
We are creating an object of list
type of Employee
class so that we can add records into that object. To retrieve data from database, create and pass the query string to SqlCommand
then by SqlDataReader
, it will read each record in database be calling Read()
method of SqlDataReader
.
Then, call this method in Home
controller.
public JsonResult getList()
{
var emp = new List<Employee>();
repository getdata = new repository();
emp = getdata.getList();
return Json(emp,JsonRequestBehavior.AllowGet);
}
Next, Delete Data From Database
For this, we are going to send model via Ajax call to our Home controller.
Write this code in Angular controller.
$scope.delete = function (data) {
var state = confirm("Do you want to delete this record");
if (state == true)
{
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
url: '/Home/delete',
success: function (status) {
console.log(status)
},
error: function (status) { }
});
}
}
First, we are going to confirm from user that he wants to delete that particular data by confirming popup which gives two results, i.e., true
or false
, if the user clicks cancel, then it'll be false
, if user clicks, then it will be true
. The if
condition checks the confirm result, and if true
then it will execute Ajax codes. Here, we are sending whole array of data to HomeController
. Create delete
function in Repository
class.
public JsonResult delete(Employee emp)
{
repository del = new repository();
del.delete(emp.id);
return null;
}
public void delete(int data)
{
con.Open();
string query = "delete from emp where id=@id";
SqlCommand cmd = new SqlCommand(query,con);
cmd.Parameters.AddWithValue("@id", data);
cmd.ExecuteNonQuery();
con.Close();
}
Here, we are sending only id as parameter to delete function in Repository
class.
Here, we are calling delete
function in homeController
.
For example, we will delete emp 4
.
Next Is to Edit and Update Records
First, write this code in first table to create a button
for update
.
<input type="button" data-ng-click="update()" value="Update" />
Create an edit button in the second table.
<tbody>
<tr data-ng-repeat="item in emplist">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.designation}}</td>
<td>{{item.mobile}}</td>
<td><input type="button"
data-ng-click="edit(item)" value="Edit" /></td>
<td><input type="button"
data-ng-click="delete(item)" value="Delete" /></td>
</tr>
</tbody>
Here, we are sending whole array model to edit function:
$scope.edit = function (index) {
$scope.emp.id = index.id;
$scope.emp.name = index.name;
$scope.emp.designation = index.designation;
$scope.emp.mobile = index.mobile;
};
Here, we are assigning the data retrieved from array model to text boxes. After editing the records, click button calls the click
function which in return does Ajax call to update function of homeController
.
By clicking on edit button, it will display the selected data in the textbox
es so that we can edit it. Here, I have selected emp 4
and edited its mobile number to 33333
.
On clicking Update button, it will send the edited data to update
method in homeController
via Ajax call.
Write this code in homeController
:
public JsonResult update(Employee emp)
{
repository up = new repository();
up.update(emp);
return null;
}
public void update(Employee emp)
{
con.Open();
string save = "update employee set name=@nm, designation=@dg, mobile=@mb where id=@id";
SqlCommand cmd = new SqlCommand(save, con);
cmd.Parameters.AddWithValue("@id", emp.id);
cmd.Parameters.AddWithValue("@nm", emp.name);
cmd.Parameters.AddWithValue("@dg", emp.designation);
cmd.Parameters.AddWithValue("@mb", emp.mobile);
cmd.ExecuteNonQuery();
con.Close();
}