CRUD Operations using ASP.NET Web API and Angular.js

Introduction:
This article explains you to save data in sql server database using ASP.NET Web API and AngularJS.
Description:
Below code is used to insert data into database using Web API and AngularJS
To implement this we need to write the code like as shown below

SQL Server :-

Before implement this example first design one table sampleinfo in your database like as shown below


HTML Java Script CSS:

Now open your aspx page and write the code like as shown below

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="../scripts-common/jquery-2.1.4.js"></script>
    <script src="../scripts-common/angular.js"></script>
    <script src="../scripts-ctrls/employeeCtrl.js"></script>
    <title>Save Employee Using Angular JS and Web API</title>

</head>
<body>
    <div ng-app="myApp" ng-controller="mainController" style="margin: auto; width: 40%;">

        <table style="border-collapse: collapse;" border="1" cellpadding="5">
            <tr>
                <td colspan="3" style="text-align: center;"><b><span id="lblmessage"></span></b></td>

            </tr>
            <tr>
                <td style="width: 100px;">Name</td>
                <td style="width: 1px;">:</td>
                <td>
                    <input type="text" id="txtName" />
                </td>
            </tr>
            <tr>
                <td>Gender</td>
                <td>:</td>
                <td>
                    <select id="ddlGender">
                        <option>Male</option>
                        <option>Female</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Department No</td>
                <td>:</td>
                <td>
                    <input type="text" id="txtDepaertment" /></td>
            </tr>
            <tr>
                <td>Salary</td>
                <td>:</td>
                <td>
                    <input type="text" id="txtSalary" />
                </td>

            </tr>
            <tr>
                <td></td>
                <td></td>
                <td>
                    <input id="btnSave" type="button" value="Save" ng-click="saveEmployee()" /></td>
            </tr>
        </table>
        <input type="hidden" id="txtId" value="0" />
    </div>
</body>
</html>

AngularJS Controller :

 
var myApp = angular.module("myApp", []);
myApp.controller("mainController", function ($scope, $http, $log) {
    $scope.title = 'Save data using AngularJS and WebAPI';

    $scope.saveEmployee = function () {

        var strEmployee = {};
        strEmployee.Id = $('#txtId').val();
        strEmployee.Name = $('#txtName').val();
        strEmployee.Gender = $('#ddlGender').val();
        strEmployee.DeptId = $('#txtDepaertment').val();
        strEmployee.Salary = $('#txtSalary').val();


        $http({
            method: 'POST',
            url: '../api/EmployeeDetails/SaveEmployee',
            params: { strEmployee: angular.toJson(strEmployee, true) }
        }).then(successCallback, errorCallback).finally(function () { });

    };


    var successCallback = function (response) {
        $('#lblmessage').html('Employee save successfully.');
    };
    var errorCallback = function (response) {
        $scope.error = response.data;
    };

});




C# :

Declare Properties
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AngularJSCURD.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public string Gender { get; set; }

        public int DeptId { get; set; }

        public int Salary { get; set; }


    }
}

C#:
ADO.NET 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace AngularJSCURD.Models
{
    public class EmployeeDBManager
    {
        string strConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
        string strSQLQuery = "";
        public int SaveEmployee(Employee objEmployee)
        {
            int Id = 0; ;
            try
            {
                strSQLQuery = "INSERT INTO tblEmployees(Name,Gender,DeptId,Salary) VALUES('" + objEmployee.Name + "','" + objEmployee.Gender + "'," + objEmployee.DeptId + "," + objEmployee.Salary + ")";
                using (SqlConnection con = new SqlConnection(strConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = strSQLQuery;
                        cmd.Connection = con;
                        con.Open();
                        Id = cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                string strEx = ex.Message;
            }

            return Id;
        }
       

    }
}

Web API:
using AngularJSCURD.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace AngularJSCURD.Controllers
{
    public class EmployeeDetailsController : ApiController
    {
        [HttpPost]
        public int SaveEmployee(string strEmployee)
        {
            int Id = 0;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Employee objEmployee = serializer.Deserialize<Employee>(strEmployee);
            EmployeeDBManager objEmployeeDBManager = new EmployeeDBManager();
            Id = objEmployeeDBManager.SaveEmployee(objEmployee);
            return Id;
        }
    }
}
DEMO

Blogger Tips and TricksLatest Tips And TricksBlogger Tricks