Click here to Skip to main content
15,391,859 members
Articles / Web Development / HTML
Article
Posted 25 Apr 2015

Stats

115.1K views
162 downloads
52 bookmarked

CRUD in ASP.MVC 4 with Angular.js

Rate me:
Please Sign up or sign in to vote.
4.82/5 (29 votes)
25 Apr 2015CPOL6 min read
CRUD in ASP.MVC 4 with scripting lang as Angular and Database as MS SQL 2008R2

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.

Image 1

Using the Code

First, we need to create a project in ASP.MVC 4 and name it as you prefer.

Image 2

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.

Image 3

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

JavaScript
bundles.Add(new Bundle("~/bundles/scripts")
                .Include("~/Scripts/angular.js")
                .Include("~/Scripts/jquery-{version}.js"));

Give reference of this bundle in Layout page.

JavaScript
@Scripts.Render("~/bundles/scripts")

Image 4

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.

JavaScript
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:

JavaScript
angular
    .module('MyApp.ctrl.crud', [])
    .controller('loginController',[
        '$scope',
        function ($scope) {
           alert("In Login Controller")
        }
    ]);

Write this code in Angular routeConfig.js file:

JavaScript
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:

  1. routeProvider.when:
    1. templateUrl: gives the virtual path of our view
    2. controller: gives the route to our view (controller)
  2. 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:

  • http://Angular.com/login

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.

JavaScript
<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.

Image 5

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.

HTML
<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.

JavaScript
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.

JavaScript
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.

JavaScript
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.

JavaScript
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).

Image 6

Now, let's check if our data is saved in database or not.

Image 7

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.

HTML
<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.

JavaScript
$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:

JavaScript
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.

JavaScript
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.

JavaScript
$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: "{ id: "+data.id+" }",
                        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.

JavaScript
// Home Controller 
public JsonResult delete(Employee emp)
        {
            repository del = new repository();
            del.delete(emp.id);
            return null;
        }

//In Repository class.

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.

Image 8

Next Is to Edit and Update Records

First, write this code in first table to create a button for update.

JavaScript
<input type="button" data-ng-click="update()" value="Update" />

Create an edit button in the second table.

HTML
<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:

JavaScript
$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 textboxes so that we can edit it. Here, I have selected emp 4 and edited its mobile number to 33333.

Image 9

On clicking Update button, it will send the edited data to update method in homeController via Ajax call.

Image 10

Write this code in homeController:

JavaScript
//homeController
public JsonResult update(Employee emp)
        {
            repository up = new repository();
            up.update(emp);
            return null;
        }

//Repository class.
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();        
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rohan Sampat
Software Developer (Junior)
India India
No Biography provided

Comments and Discussions

 
Questionnot able to extract rar file. can you upload like zip file Pin
prabhucodeproject13-Jul-16 10:44
Memberprabhucodeproject13-Jul-16 10:44 
Questionerror Pin
Member 1195623913-Dec-15 23:26
professionalMember 1195623913-Dec-15 23:26 
QuestionRegarding new route you have defined in RouteConfig.cs Pin
Arjun Mourya15-Oct-15 6:28
MemberArjun Mourya15-Oct-15 6:28 
AnswerRe: Regarding new route you have defined in RouteConfig.cs Pin
viprat19-Oct-15 2:50
Memberviprat19-Oct-15 2:50 
AnswerRe: Regarding new route you have defined in RouteConfig.cs Pin
Rohan Sampat2-Dec-15 19:23
professionalRohan Sampat2-Dec-15 19:23 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-May-15 18:10
MemberHumayun Kabir Mamun10-May-15 18:10 
Generaluser $http instead of jquery ajax (or $resource if you could convert your MVC app to webapi and make it restful) Pin
Rahul Rajat Singh7-May-15 23:15
professionalRahul Rajat Singh7-May-15 23:15 
I saw the code and it seems to work so Kudos to that.

The Routing part also seems to glued up pretty well. But I am little confused about the use of jquery. Why not use $http or $resource for the ajax operations. Using $ajax is also forcing you to use scope.apply which is not needed if you start using $http and handle the promises.

Also, from a best practice and architecture perspective, we should have an EmployeeService that should be using either $http or $resource and the controller should be using this service. Our controllers should be lean and should only deal with responding to the UI events/data/action talking to the service and then sending the result back to the view.

Anyways, I hope you will find these comments useful and I can see this is your debut article so welcome to CodeProject. +3 from me for the effort.

GeneralRe: user $http instead of jquery ajax (or $resource if you could convert your MVC app to webapi and make it restful) Pin
Rohan Sampat23-May-15 23:12
professionalRohan Sampat23-May-15 23:12 
QuestionNice Article Pin
Santhakumar Munuswamy @ Chennai3-May-15 5:32
professionalSanthakumar Munuswamy @ Chennai3-May-15 5:32 
QuestionWith Stored Procedure Pin
coded00729-Apr-15 21:59
professionalcoded00729-Apr-15 21:59 
SuggestionNone of your images (except code listings) are working Pin
Andreas Kroll27-Apr-15 0:37
MemberAndreas Kroll27-Apr-15 0:37 
GeneralRe: None of your images (except code listings) are working Pin
Rohan Sampat28-Apr-15 2:36
professionalRohan Sampat28-Apr-15 2:36 
GeneralRe: None of your images (except code listings) are working Pin
Andreas Kroll28-Apr-15 6:50
MemberAndreas Kroll28-Apr-15 6:50 
GeneralAttach Source Code Pin
Sujeet Bhujbal26-Apr-15 23:38
MemberSujeet Bhujbal26-Apr-15 23:38 
GeneralRe: Attach Source Code Pin
lcorderof28-Apr-15 18:47
professionallcorderof28-Apr-15 18:47 
QuestionOne suggestion Pin
Tridip Bhattacharjee26-Apr-15 21:55
professionalTridip Bhattacharjee26-Apr-15 21:55 
AnswerRe: One suggestion Pin
Rohan Sampat7-May-15 1:50
professionalRohan Sampat7-May-15 1:50 
AnswerSuggestion about this post... Pin
Afzaal Ahmad Zeeshan26-Apr-15 1:39
mveAfzaal Ahmad Zeeshan26-Apr-15 1:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.