In Focus

CRUD Operations Using Angular And ASP.NET Web Services

This is the page for adding category and subcategory,in this page there is a dropdownlist to which all categories are binded,the user will have option to select category and add a subcategory for the category.If he wants to add new category he will select add new option from the dropdownlist.Here is how the page will look like when he selects add new option.

There are two pages - one for adding or updating category and subcategory or deleting the subcategory. Other for updating and deleting category.Here is how the pages will look like,

 
This is the page for adding category and subcategory,in this page there is a dropdownlist to which all categories are binded,the user will have option to select category and add a subcategory for the category.If he wants to add new category he will select add new option from the dropdownlist.Here is how the page will look like when he selects add new option.

 
When user selects add new option from drop down the category textbox,subcategory name textbox and file upload control along with submit button will be visible.When category is selected only subcategory name textbox and file upload control and submit button will be visible.Here is how the page will look when user selects category instead of add new option from dropdown

 

When edit button is clicked,subcategory name and category will be shown in textbox and dropdown respectively and update and cancel button will be visible and submit button will be hidden.Cancel button is if the user wants to cancel the updation.Here is how the page looks when user clicks on edit button

 
Below is the page from which user can update or delete a category.This page will open when user clicks on edit category link
 
Now open sql server and create two tables name it as tblCat and tblSubCat,here is the script to create tables
  1. Create table tblCat  
  2. (  
  3.    CatId int identity(1,1) Not Null,  
  4.    CatName varchar(50),  
  5.    IsActive bit Null  
  6. )  
  7. Create table tblSubCat  
  8. (  
  9.    SubCatId int identity(1,1) Not Null,  
  10.    CatId int,  
  11.    SubCatName varchar(50),  
  12.    imgPath varchar(50),  
  13.    IsActive bit  
  14. )  
Now create two store procedures to add update category and subcategory respectively here are the two store procedures
  1. CREATE PROCEDURE Insert_update_delete_category (@Para     VARCHAR(50) = '',   
  2.                                                 @CatId    INT = 0,   
  3.                                                 @CatName  VARCHAR(50) = '',   
  4.                                                 @IsActive BIT = 0)   
  5. AS   
  6.   BEGIN   
  7.       IF @Para = 'Add'   
  8.         BEGIN   
  9.             IF EXISTS(SELECT 1   
  10.                       FROM   tblcat   
  11.                       WHERE  catname = @CatName)   
  12.               BEGIN   
  13.                   SELECT 'Exists'   
  14.               END   
  15.             ELSE   
  16.               BEGIN   
  17.                   INSERT INTO tblcat   
  18.                               (catname,   
  19.                                isactive)   
  20.                   VALUES      (@CatName,   
  21.                                1)   
  22.               END   
  23.         END   
  24.       ELSE IF @Para = 'SelectForGrid'   
  25.         BEGIN   
  26.             SELECT catid,   
  27.                    catname   
  28.             FROM   tblcat   
  29.             WHERE  isactive = 1   
  30.         END   
  31.       ELSE IF @Para = 'SelectById'   
  32.         BEGIN   
  33.             SELECT catid,   
  34.                    catname   
  35.             FROM   tblcat   
  36.             WHERE  isactive = 1   
  37.                    AND catid = @CatId   
  38.         END   
  39.       ELSE IF @Para = 'Update'   
  40.         BEGIN   
  41.             UPDATE tblcat   
  42.             SET    catname = @CatName,   
  43.                    isactive = 1   
  44.             WHERE  catid = @CatId   
  45.         END   
  46.       ELSE IF @Para = 'Delete'   
  47.         BEGIN   
  48.             UPDATE tblcat   
  49.             SET    isactive = 0   
  50.             WHERE  catid = @CatId   
  51.         END   
  52.   END   
  53.   
  54. CREATE PROCEDURE Insert_delete_update_subcat (@Para       VARCHAR(50)='',   
  55.                                               @SubCatId   INT = 0,   
  56.                                               @CatId      INT = 0,   
  57.                                               @CatName    VARCHAR(50) = '',   
  58.                                               @SubCatName VARCHAR(50) = '',   
  59.                                               @imgPath    VARCHAR(50) = '',   
  60.                                               @IsActive   BIT = 0)   
  61. AS   
  62.   BEGIN   
  63.       IF @Para = 'Add'   
  64.         BEGIN   
  65.             IF Len(@CatName) > 0   
  66.               BEGIN   
  67.                   EXEC Insert_update_delete_category   
  68.                     'Add',   
  69.                     0,   
  70.                     @CatName,   
  71.                     1   
  72.   
  73.                   SELECT @CatId = Max(catid)   
  74.                   FROM   tblcat   
  75.   
  76.                   INSERT INTO tblsubcat   
  77.                               (catid,   
  78.                                subcatname,   
  79.                                imgpath,   
  80.                                isactive)   
  81.                   VALUES      (@CatId,   
  82.                                @SubCatName,   
  83.                                @imgPath,   
  84.                                1)   
  85.               END   
  86.             ELSE   
  87.               BEGIN   
  88.                   INSERT INTO tblsubcat   
  89.                               (catid,   
  90.                                subcatname,   
  91.                                imgpath,   
  92.                                isactive)   
  93.                   VALUES      (@CatId,   
  94.                                @SubCatName,   
  95.                                @imgPath,   
  96.                                1)   
  97.               END   
  98.         END   
  99.       ELSE IF @Para = 'GetCat'   
  100.         BEGIN   
  101.             SELECT catid,   
  102.                    catname   
  103.             FROM   tblcat   
  104.             WHERE  isactive = 1   
  105.         END   
  106.       ELSE IF @Para = 'GetForGrid'   
  107.         BEGIN   
  108.             SELECT S.subcatid,   
  109.                    C.catname,   
  110.                    S.subcatname,   
  111.                    S.imgpath   
  112.             FROM   tblcat C   
  113.                    JOIN tblsubcat S   
  114.                      ON C.catid = S.catid   
  115.             WHERE  S.isactive = 1   
  116.                    AND C.isactive = 1   
  117.         END   
  118.       ELSE IF @Para = 'GetById'   
  119.         BEGIN   
  120.             SELECT C.catid,   
  121.                    C.catname,   
  122.                    S.subcatid,   
  123.                    imgpath,   
  124.                    S.subcatname   
  125.             FROM   tblsubcat S   
  126.                    JOIN tblcat C   
  127.                      ON C.catid = S.catid   
  128.             WHERE  subcatid = @SubCatId   
  129.                    AND S.isactive = 1   
  130.         END   
  131.       ELSE IF @Para = 'Update'   
  132.         BEGIN   
  133.             UPDATE tblsubcat   
  134.             SET    subcatname = @SubCatName,   
  135.                    imgpath = @imgPath,   
  136.                    isactive = 1   
  137.             WHERE  catid = @CatId   
  138.                    AND subcatid = @SubCatId   
  139.         END   
  140.       ELSE IF @Para = 'GetByCatId'   
  141.         BEGIN   
  142.             SELECT S.subcatid,   
  143.                    C.catname,   
  144.                    S.subcatname,   
  145.                    S.imgpath   
  146.             FROM   tblcat C   
  147.                    JOIN tblsubcat S   
  148.                      ON C.catid = S.catid   
  149.             WHERE  S.isactive = 1   
  150.                    AND C.isactive = 1   
  151.                    AND S.catid = @CatId   
  152.         END   
  153.       ELSE IF @Para = 'Delete'   
  154.         BEGIN   
  155.             UPDATE tblsubcat   
  156.             SET    isactive = 0   
  157.             WHERE  subcatid = @SubCatId   
  158.         END   
  159.   END   
Now open visual studio,select File-New-Project and from template select asp.net webform application and give a name to it,in my case it is WebApplication12.

Now right click on project in solutions explorer,select add new item and from template select code and select class.Name the class as Category and add a Category class to application and write the following code in class
  1. public class Category {  
  2.     public int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public int SubCatId {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string CatName {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string SubCatName {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string ImgPath {  
  19.         get;  
  20.         set;  
  21.     }  
  22. }  
Category class will contain five properties Id,SubCatId,CatName,SubCatName,ImgPath

Right click on project in solutions explorer and select add-new folder and name it as Images,in this folder uploaded images will be saved.

In the web.config add a connection string inside connectionStrings tag
  1. <connectionStrings>  
  2.     <add name="dbConnect" providerName="System.Data.SqlClient" connectionString="Data Source = LIVINGROOM\SQLEXPRESS;Initial Catalog=codefirstDB;Integrated Security=true;" />   
  3. </connectionStrings>  
here dbConnect is name given to connectionstring,DataSource is server name which is LIVINGROOM\SQLEXPRESS in my case,Initial Catalog is database name which is codefirstDB and Integrated Security is true and also write following code inside system.web tag
  1. <webServices>  
  2.     <protocols>  
  3.         <add name="HttpGet" />  
  4.         <add name="HttpPost" /> </protocols>  
  5. </webServices> 
Right click on application and select add new item,add a new asmx webservice and give a name to it.I have given WebService3

Now write the following code in web services and uncomment the following line System.Web.Services.ScriptService
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());  
  2. SqlCommand cmd = null;  
  3. DataTable dt;  
  4. SqlDataAdapter da = null;  
  5. [WebMethod]  
  6. public int InsertCat(string Category, string CatName, string SubCatName, string File) {  
  7.         string message = string.Empty;  
  8.         using(cmd = new SqlCommand("Insert_Delete_Update_SubCat", con)) {  
  9.             cmd.CommandType = CommandType.StoredProcedure;  
  10.             cmd.Parameters.AddWithValue("@Para""Add");  
  11.             if (Category == "Add New") {  
  12.                 cmd.Parameters.AddWithValue("@CatName", CatName);  
  13.             } else {  
  14.                 cmd.Parameters.AddWithValue("@CatId", Convert.ToInt32(Category));  
  15.             }  
  16.             cmd.Parameters.AddWithValue("@SubCatName", SubCatName);  
  17.             cmd.Parameters.AddWithValue("@imgPath", File);  
  18.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  19.             int result = cmd.ExecuteNonQuery();  
  20.             con.Close();  
  21.             return result;  
  22.         }  
  23.     }  
  24.     [WebMethod]  
  25. public void GetAllDetails() {  
  26.         List < Category > catList = new List < Category > ();  
  27.         using(cmd = new SqlCommand("Insert_Delete_Update_SubCat", con)) {  
  28.             cmd.CommandType = CommandType.StoredProcedure;  
  29.             cmd.Parameters.AddWithValue("@Para""GetForGrid");  
  30.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  31.             SqlDataReader dr = cmd.ExecuteReader();  
  32.             while (dr.Read()) {  
  33.                 Category cat = new Category();  
  34.                 cat.SubCatId = Convert.ToInt32(dr["SubCatId"]);  
  35.                 cat.CatName = dr["CatName"].ToString();  
  36.                 cat.SubCatName = dr["SubCatName"].ToString();  
  37.                 cat.ImgPath = dr["imgPath"].ToString();  
  38.                 catList.Add(cat);  
  39.             }  
  40.             con.Close();  
  41.             JavaScriptSerializer js = new JavaScriptSerializer();  
  42.             Context.Response.Write(js.Serialize(catList));  
  43.         }  
  44.     }  
  45.     [WebMethod]  
  46. public void GetCatList() {  
  47.         List < Category > catlist = new List < Category > ();  
  48.         using(cmd = new SqlCommand("Insert_Delete_Update_SubCat", con)) {  
  49.             cmd.CommandType = CommandType.StoredProcedure;  
  50.             cmd.Parameters.AddWithValue("@Para""GetCat");  
  51.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  52.             SqlDataReader dr = cmd.ExecuteReader();  
  53.             while (dr.Read()) {  
  54.                 Category cat = new Category();  
  55.                 cat.Id = Convert.ToInt32(dr["CatId"]);  
  56.                 cat.CatName = dr["CatName"].ToString();  
  57.                 catlist.Add(cat);  
  58.             }  
  59.         }  
  60.         JavaScriptSerializer js = new JavaScriptSerializer();  
  61.         Context.Response.Write(js.Serialize(catlist));  
  62.     }  
  63.     [WebMethod]  
  64. public string GetById(string Id) {  
  65.         string Result = string.Empty;  
  66.         using(cmd = new SqlCommand("Insert_Delete_Update_SubCat", con)) {  
  67.             cmd.CommandType = CommandType.StoredProcedure;  
  68.             cmd.Parameters.AddWithValue("@Para""GetById");  
  69.             cmd.Parameters.AddWithValue("@SubCatId", Convert.ToInt32(Id));  
  70.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  71.             dt = new DataTable();  
  72.             da = new SqlDataAdapter(cmd);  
  73.             da.Fill(dt);  
  74.             if (dt.Rows.Count > 0) {  
  75.                 Result = "{\"CatId\":";  
  76.                 Result += "\"" + dt.Rows[0][0].ToString() + "\",";  
  77.                 Result += "\"CatName\":\"" + dt.Rows[0][1].ToString() + "\",";  
  78.                 Result += "\"SubCatId\":\"" + dt.Rows[0][2].ToString() + "\",";  
  79.                 Result += "\"Path\":\"" + dt.Rows[0][3].ToString() + "\",";  
  80.                 Result += "\"SubCatName\":\"" + dt.Rows[0][4].ToString() + "\"";  
  81.                 Result += "}";  
  82.             }  
  83.             con.Close();  
  84.             return Result;  
  85.         }  
  86.     }  
  87.     [WebMethod]  
  88. public int UpdateSubCat(string Category, string SubCatName, string subCatId, string File) {  
  89.         string message = string.Empty;  
  90.         using(cmd = new SqlCommand("Insert_Delete_Update_SubCat", con)) {  
  91.             cmd.CommandType = CommandType.StoredProcedure;  
  92.             cmd.Parameters.AddWithValue("@Para""Update");  
  93.             cmd.Parameters.AddWithValue("@CatId", Convert.ToInt32(Category));  
  94.             cmd.Parameters.AddWithValue("@subCatId", Convert.ToInt32(subCatId));  
  95.             cmd.Parameters.AddWithValue("@SubCatName", SubCatName);  
  96.             cmd.Parameters.AddWithValue("@imgPath", File);  
  97.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  98.             int result = cmd.ExecuteNonQuery();  
  99.             con.Close();  
  100.             return result;  
  101.         }  
  102.     }  
  103.     [WebMethod]  
  104. public void GetByCategory(string Id) {  
  105.         List < Category > catList = new List < Category > ();  
  106.         using(cmd = new SqlCommand("Insert_Delete_Update_SubCat", con)) {  
  107.             cmd.CommandType = CommandType.StoredProcedure;  
  108.             cmd.Parameters.AddWithValue("@Para""GetByCatId");  
  109.             cmd.Parameters.AddWithValue("@CatId", Convert.ToInt32(Id));  
  110.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  111.             SqlDataReader dr = cmd.ExecuteReader();  
  112.             while (dr.Read()) {  
  113.                 Category cat = new Category();  
  114.                 cat.SubCatId = Convert.ToInt32(dr["SubCatId"]);  
  115.                 cat.CatName = dr["CatName"].ToString();  
  116.                 cat.SubCatName = dr["SubCatName"].ToString();  
  117.                 cat.ImgPath = dr["imgPath"].ToString();  
  118.                 catList.Add(cat);  
  119.             }  
  120.             con.Close();  
  121.             JavaScriptSerializer js = new JavaScriptSerializer();  
  122.             Context.Response.Write(js.Serialize(catList));  
  123.         }  
  124.     }  
  125.     [WebMethod]  
  126. public int DeleteSubCat(string Id) {  
  127.         string message = string.Empty;  
  128.         using(cmd = new SqlCommand("Insert_Delete_Update_SubCat", con)) {  
  129.             cmd.CommandType = CommandType.StoredProcedure;  
  130.             cmd.Parameters.AddWithValue("@Para""Delete");  
  131.             cmd.Parameters.AddWithValue("@SubCatId", Convert.ToInt32(Id));  
  132.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  133.             int result = cmd.ExecuteNonQuery();  
  134.             con.Close();  
  135.             return result;  
  136.         }  
  137.     }  
  138.     [WebMethod]  
  139. public void GetCategory() {  
  140.         List < Category > catlist = new List < Category > ();  
  141.         using(cmd = new SqlCommand("Insert_Update_Delete_Category", con)) {  
  142.             cmd.CommandType = CommandType.StoredProcedure;  
  143.             cmd.Parameters.AddWithValue("@Para""SelectForGrid");  
  144.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  145.             SqlDataReader dr = cmd.ExecuteReader();  
  146.             while (dr.Read()) {  
  147.                 Category cat = new Category();  
  148.                 cat.Id = Convert.ToInt32(dr["CatId"]);  
  149.                 cat.CatName = dr["CatName"].ToString();  
  150.                 catlist.Add(cat);  
  151.             }  
  152.         }  
  153.         JavaScriptSerializer js = new JavaScriptSerializer();  
  154.         Context.Response.Write(js.Serialize(catlist));  
  155.     }  
  156.     [WebMethod]  
  157. public string GetCatById(string Id) {  
  158.         string Result = string.Empty;  
  159.         using(cmd = new SqlCommand("Insert_Update_Delete_Category", con)) {  
  160.             cmd.CommandType = CommandType.StoredProcedure;  
  161.             cmd.Parameters.AddWithValue("@Para""SelectById");  
  162.             cmd.Parameters.AddWithValue("@CatId", Convert.ToInt32(Id));  
  163.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  164.             dt = new DataTable();  
  165.             da = new SqlDataAdapter(cmd);  
  166.             da.Fill(dt);  
  167.             if (dt.Rows.Count > 0) {  
  168.                 Result = "{\"Id\":";  
  169.                 Result += "\"" + dt.Rows[0][0].ToString() + "\",";  
  170.                 Result += "\"CatName\":\"" + dt.Rows[0][1].ToString() + "\"";  
  171.                 Result += "}";  
  172.             }  
  173.             con.Close();  
  174.             return Result;  
  175.         }  
  176.     }  
  177.     [WebMethod]  
  178. public int UpdateCat(string Id, string CatName) {  
  179.         string message = string.Empty;  
  180.         using(cmd = new SqlCommand("Insert_Update_Delete_Category", con)) {  
  181.             cmd.CommandType = CommandType.StoredProcedure;  
  182.             cmd.Parameters.AddWithValue("@Para""Update");  
  183.             cmd.Parameters.AddWithValue("@CatId", Convert.ToInt32(Id));  
  184.             cmd.Parameters.AddWithValue("@CatName", CatName);  
  185.             if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  186.             int result = cmd.ExecuteNonQuery();  
  187.             con.Close();  
  188.             return result;  
  189.         }  
  190.     }  
  191.     [WebMethod]  
  192. public int DeleteCat(string Id) {  
  193.     string message = string.Empty;  
  194.     using(cmd = new SqlCommand("Insert_Update_Delete_Category", con)) {  
  195.         cmd.CommandType = CommandType.StoredProcedure;  
  196.         cmd.Parameters.AddWithValue("@Para""Delete");  
  197.         cmd.Parameters.AddWithValue("@CatId", Convert.ToInt32(Id));  
  198.         if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  199.         int result = cmd.ExecuteNonQuery();  
  200.         con.Close();  
  201.         return result;  
  202.     }  
  203. }  
As we can see the webservice contains 11 methods,first method is InsertCat which is used to insert category and subcategory.In this method if user has selected add new option then category name will be inserted and Id will be generated automatically for that category in database.But if category which is already present is selected then its Id will be inserted.File is the image name that is stored in databse for subcategory.
  • Second method is GetAllDetails which returns the list of Categories and SubCategories which will be shown to the user on page load.
  • Third method is GetCatList which is used to select Cateogory Name and Id which will be binded with dropdownlist
  • Fourth method is GetById which fetches the subcategory details on the basis of its Id for editing.From that I have return a string result which syntax is similar to javascript object which I have created using escape sequences in C#
  • Fifth method is UpdateSubCat which is used to update subcategory details
  • Sixth method is GetByCategory which is used to get SubCategory based on category selected by user in dropdown.
  • Seventh method is DeleteSubCat which is used to delete subcategory
  • Eigth method is GetCategory which will provide list of Cateogory for updating and deleting when user clicks edit category link
  • Ninth method is GetCatById which is use to select catName by Id for updation
  • Tenth method is UpdateCat which is use to update catName on basis of CatId
  • Last method is DeleteCat which is use to delete category
Now right click on application select Add-New-Item and from template select web and then select Generic Handler and add an ashx handler which will be used to store images inside Image folder when user uploads it.Give a name to handler I have given name as Handler1 and write the following code in it inside process request.
  1. public void ProcessRequest(HttpContext context) {  
  2.     context.Response.ContentType = "text/plain";  
  3.     if (context.Request.Files.Count > 0) {  
  4.         HttpFileCollection files = context.Request.Files;  
  5.         for (int i = 0; i < files.Count; i++) {  
  6.             HttpPostedFile file = files[i];  
  7.             string fileType = file.ContentType;  
  8.             if (fileType == "image/jpeg" || fileType == "image/png") {  
  9.                 string fname = file.FileName;  
  10.                 bool folderExists = Directory.Exists(context.Server.MapPath("~/Images/"));  
  11.                 if (!folderExists) Directory.CreateDirectory(context.Server.MapPath("~/Images/"));  
  12.                 fname = Path.Combine(context.Server.MapPath("~/Images/"), fname);  
  13.                 file.SaveAs(fname);  
  14.                 context.Response.ContentType = "text/plain";  
  15.                 context.Response.Write("File Uploaded Successfully!");  
  16.             } else {  
  17.                 context.Response.ContentType = "text/plain";  
  18.                 context.Response.Write("File Not Uploaded Successfully,Extension should be jpeg or png");  
  19.             }  
  20.         }  
  21.     }  
  22. }  
This request will be called when user uploads image and clicks submit button or update button.In this method I have checked content type if it is image/jpeg or image/png file will be stored inside Images folder otherwise it will not be stored and base upon that message will be return to the user.

Now right click on application and add a new javascript file with .js extension.And Give a name to it,I have given it name as Javascript19.And Write the following code on it.This is used for inserting category,subcategory and updating subcategory
  1. /// <reference path="angular.min.js" />  
  2. /// <reference path="jquery-1.8.2.min.js" />  
  3. var myApp = angular.module("myModule", []).directive("filesInput"function() {  
  4.     return {  
  5.         require: "ngModel",  
  6.         link: function postLink(scope, elem, attrs, ngModel) {  
  7.             elem.on("change"function(e) {  
  8.                 var files = elem[0].files;  
  9.                 ngModel.$setViewValue(files);  
  10.             })  
  11.         }  
  12.     }  
  13. }).controller("myController"function($scope, $http) {  
  14.     $scope.category = "0";  
  15.     $scope.cat = false;  
  16.     $scope.subcat = false;  
  17.     $scope.sumbmitbutton = false;  
  18.     $scope.showEditUpdate = false;  
  19.     $scope.showGrid = false;  
  20.     GetAllRecords();  
  21.     $scope.ShowHideDiv = function(category) {  
  22.         if (category == "Add New") {  
  23.             $scope.cat = true;  
  24.             $scope.subcat = true;  
  25.             $scope.sumbmitbutton = true;  
  26.             $scope.showEditUpdate = false;  
  27.             $scope.subCatName = '';  
  28.             $scope.catName = '';  
  29.             GetAllRecords();  
  30.         } else if (category == "0") {  
  31.             $scope.cat = false;  
  32.             $scope.subcat = false;  
  33.             $scope.sumbmitbutton = false;  
  34.             $scope.showEditUpdate = false;  
  35.             $scope.catName = '';  
  36.             $scope.subCatName = '';  
  37.             $scope.file = '';  
  38.             $("#filebutton").val('');  
  39.             GetAllRecords();  
  40.         } else {  
  41.             $scope.cat = false;  
  42.             $scope.subcat = true;  
  43.             $scope.sumbmitbutton = true;  
  44.             $scope.showEditUpdate = false;  
  45.             $scope.subCatName = '';  
  46.             $scope.catName = '';  
  47.             $scope.file = '';  
  48.             $("#filebutton").val('');  
  49.             var config = {  
  50.                 params: {  
  51.                     Id: category  
  52.                 }  
  53.             }  
  54.             $http.get('WebService3.asmx/GetByCategory', config).then(function(response) {  
  55.                 if (response.data.length > 0) {  
  56.                     $scope.categoryDetails = response.data;  
  57.                     $scope.showGrid = true;  
  58.                 }  
  59.             })  
  60.         }  
  61.     }  
  62.     $scope.InsertData = function(category, catName, subCatName, file) {  
  63.         var FileName = "";  
  64.         var msg = "";  
  65.         if (category == "0" || category == undefined) {  
  66.             msg += "Please Select Category, ";  
  67.         }  
  68.         if (category == "Add New") {  
  69.             if (catName == '' || catName == undefined) {  
  70.                 msg += "Please Enter Category Name, ";  
  71.             }  
  72.         }  
  73.         if (subCatName == '' || subCatName == undefined) {  
  74.             msg += "Please Enter SubCategory Name, ";  
  75.         }  
  76.         if (file == '' || file == undefined) {  
  77.             msg += "Please Select Image, ";  
  78.         }  
  79.         if (msg.length > 0) {  
  80.             msg = msg.substring(0, msg.length - 2);  
  81.             alert(msg);  
  82.         } else {  
  83.             var Cat = category;  
  84.             var CatName = catName;  
  85.             var SubCatName = subCatName;  
  86.             var SubCatId = 0;  
  87.             FileName = file[0].name;  
  88.             UploadFile(Cat, CatName, SubCatName, FileName, SubCatId);  
  89.         }  
  90.     }  
  91.     $scope.catList = function() {  
  92.         $http({  
  93.             method: 'Get',  
  94.             url: 'WebService3.asmx/GetCatList',  
  95.         }).then(function(result) {  
  96.             $scope.CategoryList = result.data;  
  97.         })  
  98.     }  
  99.     $scope.catList();  
  100.   
  101.     function clear() {  
  102.         $scope.catName = '';  
  103.         $('#txtCategory').val('');  
  104.         $scope.subCatName = '';  
  105.         $('#txtSubCategory').val('');  
  106.         $scope.file = '';  
  107.         $("#filebutton").val('');  
  108.         $scope.category = "0";  
  109.         $scope.cat = false;  
  110.         $scope.subcat = false;  
  111.         $scope.sumbmitbutton = false;  
  112.         $scope.showEditUpdate = false;  
  113.     }  
  114.   
  115.     function GetAllRecords() {  
  116.         $http({  
  117.             method: 'Get',  
  118.             url: 'WebService3.asmx/GetAllDetails'  
  119.         }).then(function(response) {  
  120.             if (response.data.length > 0) {  
  121.                 $scope.categoryDetails = response.data;  
  122.                 $scope.showGrid = true;  
  123.             }  
  124.         })  
  125.     }  
  126.     $scope.EditSubCat = function(Id) {  
  127.         $http({  
  128.             method: 'Post',  
  129.             url: 'WebService3.asmx/GetById',  
  130.             data: "{'Id' : '" + Id + "'}",  
  131.             contentType: "application/json; charset=utf-8",  
  132.             dataType: "json"  
  133.         }).then(function(response) {  
  134.             if (response.data.d.length > 0) {  
  135.                 var Result = jQuery.parseJSON(response.data.d);  
  136.                 $scope.SubCatId = Result.SubCatId;  
  137.                 $scope.subCatName = Result.SubCatName;  
  138.                 $scope.category = Result.CatId;  
  139.                 $scope.file = '';  
  140.                 $("#filebutton").val('');  
  141.                 $scope.subcat = true;  
  142.                 $scope.cat = false;  
  143.                 $scope.sumbmitbutton = false;  
  144.                 $scope.showEditUpdate = true;  
  145.             }  
  146.         })  
  147.     }  
  148.     $scope.UpdateData = function(category, subCatName, SubCatId, file) {  
  149.         var FileName = "";  
  150.         var msg = "";  
  151.         if (category == "0" || category == undefined) {  
  152.             msg += "Please Select Category, ";  
  153.         }  
  154.         if (subCatName == '' || subCatName == undefined) {  
  155.             msg += "Please Enter SubCategory Name, ";  
  156.         }  
  157.         if (file == '' || file == undefined) {  
  158.             msg += "Please Select Image, ";  
  159.         }  
  160.         if (msg.length > 0) {  
  161.             msg = msg.substring(0, msg.length - 2);  
  162.             alert(msg);  
  163.         } else {  
  164.             var Cat = category;  
  165.             var CatName = "";  
  166.             var SubCatName = subCatName;  
  167.             var SubCatId = SubCatId;  
  168.             FileName = file[0].name;  
  169.             UploadFile(Cat, CatName, SubCatName, FileName, SubCatId);  
  170.         }  
  171.     }  
  172.     $scope.CancelUpdate = function() {  
  173.         clear();  
  174.         GetAllRecords();  
  175.     }  
  176.     $scope.DeleteData = function(SubCatId) {  
  177.         if (window.confirm("Are you sure you want to Delete this record?")) $scope.result = "Yes";  
  178.         else $scope.result = "No";  
  179.         if ($scope.result == "Yes") {  
  180.             $http({  
  181.                 method: 'Post',  
  182.                 url: 'WebService3.asmx/DeleteSubCat',  
  183.                 data: "{'Id' : '" + SubCatId + "'}",  
  184.                 contentType: "application/json; charset=utf-8",  
  185.                 dataType: "json"  
  186.             }).then(function(response) {  
  187.                 clear();  
  188.                 if (response.data.d > 0) {  
  189.                     alert("Record Deleted Successfully");  
  190.                     GetAllRecords();  
  191.                 } else {  
  192.                     alert("Record Not Deleted");  
  193.                     GetAllRecords();  
  194.                 }  
  195.             })  
  196.         }  
  197.     }  
  198.   
  199.     function UploadFile(Cat, CatName, SubCatName, FileName, SubCatId) {  
  200.         var fileUpload = $('#filebutton').get(0);  
  201.         $log.info(fileUpload);  
  202.         var files = fileUpload.files;  
  203.         $log.info(files);  
  204.         var test = new FormData();  
  205.         for (var i = 0; i < files.length; i++) {  
  206.             test.append(files[i].name, files[i]);  
  207.             $log.info(test);  
  208.         }  
  209.         $.ajax({  
  210.             url: "Handler1.ashx",  
  211.             type: "POST",  
  212.             contentType: false,  
  213.             processData: false,  
  214.             data: test,  
  215.             success: function(result) {  
  216.                 if (result == "File Uploaded Successfully!") {  
  217.                     if ($scope.sumbmitbutton == true) {  
  218.                         $http({  
  219.                             method: 'Post',  
  220.                             url: 'WebService3.asmx/InsertCat',  
  221.                             data: "{'Category' : '" + Cat + "','CatName' : '" + CatName + "','SubCatName' : '" + SubCatName + "','File' : '" + FileName + "'}",  
  222.                             contentType: "application/json; charset=utf-8",  
  223.                             dataType: "json"  
  224.                         }).then(function(response) {  
  225.                             clear();  
  226.                             if (response.data.d > 0) {  
  227.                                 alert("Record Inserted Successfully");  
  228.                                 $scope.catList();  
  229.                                 GetAllRecords();  
  230.                             } else {  
  231.                                 alert("Entry Already Exists");  
  232.                                 $scope.catList();  
  233.                                 GetAllRecords();  
  234.                             }  
  235.                         })  
  236.                     }  
  237.                     if ($scope.showEditUpdate == true) {  
  238.                         $http({  
  239.                             method: 'Post',  
  240.                             url: 'WebService3.asmx/UpdateSubCat',  
  241.                             data: "{'Category' : '" + Cat + "','SubCatName' : '" + SubCatName + "','subCatId' : '" + SubCatId + "','File' : '" + FileName + "'}",  
  242.                             contentType: "application/json; charset=utf-8",  
  243.                             dataType: "json"  
  244.                         }).then(function(response) {  
  245.                             clear();  
  246.                             if (response.data.d > 0) {  
  247.                                 alert("Record Updated Successfully");  
  248.                                 $scope.catList();  
  249.                                 GetAllRecords();  
  250.                             } else {  
  251.                                 alert("Record Not Updated Successfully");  
  252.                                 $scope.catList();  
  253.                                 GetAllRecords();  
  254.                             }  
  255.                         })  
  256.                     }  
  257.                 } else {  
  258.                     alert(result);  
  259.                     $scope.file = '';  
  260.                     $("#filebutton").val('');  
  261.                 }  
  262.             }  
  263.         });  
  264.     }  
  265. })  
Now first line is angular.min.js script file which you can download from angularjs.org And second is jquery-1.8.2.min.js which I have downloaded from net and added reference of it in project.you need to add reference of this script files and order is also important.

Now second line is to create a module angular object's module method is used to create a module and to it first parameter passed is module name which is myModule and second parameter is optional if there is any dependency on module that name will be provided here.this module will be call using ng-app directive on our html page.

Then there is a directive which name is filesInput which will store the uploaded files by user

Then there is controller to it first parameter is controller name which is myController which will be fetched using ng-controller directive on html page.To the controller I have passed $scope to which we will assign property and to that property we will assign value.And use this property name on html page.Another one is $http which is used to call webmethods in webservice.which has various properties such as method which is the type of method which will be get or post.url that is the url of webmethod,data which to be pass to webmethod. Contenttype and datatype which tells us what type of data is return by user.

Inside the controller the properties are attached to $scope object first is category which is initialized to zero so when page loads,user will see Select option in dropdown for category.Other properties are cat,subcat which are set to false because initially the user will see only category dropdown.Next properties are submitbutton and showEditUpdate set to false this will set to true accordingly when user wants to enter new subcategory and when user clicks on edit button.Next property is showgrid set to false which will be made true when we fetch subcategory details present and grid will be displayed.

Now on next line GetAllRecords method is called which is used to display subcategory details in gridview on page load, Next function is insertData to which I have passed category selected by user,catName entered by user,subcatname and file name which is image name uploaded by user.Here first check is made so that user enters all the data.And then UploadFile method is called.To uploadFile method this parameters are passed.In upload file first request is made to Handler which is used to store image in Images folder,and if image is uploaded successfully then only record is inserted into database otherwise it will not be inserted.

Then there is catList function called on page load to bind categories to category dropdown, In EditSubCat method the SubCategory details are selected base on subcatId for updating.

UpdateData method is used to update the subcategory details and in this method also first uploafile method is called,so the updated image is store inside image folder and if image is uploaded successfully then only record is updated otherwise it will not be updated.Inside uploaded file I have checked two property values submitbutton and showEditUpdate depending on which one is true submit or update method will be called,
  • DeleteData is use to delete subcategory record
  • CancelUpdate if user wants to cancel updation
  • Clear function is use to clear all values after insertion or updation
ShowHideDiv which will be called on value selected in category dropdown and set the required properties to true or false base on category value selected by user.

Now right click on application and add a htmlpage give a name to it.I have given name as HtmlPage42 and write following code on it
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml" ng-app="myModule">  
  3.   
  4. <head>  
  5.     <script src="Scripts/angular.min.js" type="text/javascript" lang="ja"></script>  
  6.     <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript" lang="ja"></script>  
  7.     <script src="Scripts/JavaScript19.js" type="text/javascript" lang="ja"></script>  
  8.     <script type="text/javascript" lang="ja">  
  9.         function ValidateCatName(e) {  
  10.             var keyCode = (e.which) ? e.which : e.keyCode  
  11.             if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32) {  
  12.                 return true;  
  13.             } else {  
  14.                 return false;  
  15.             }  
  16.         }  
  17.   
  18.         function ValidateSubCatName(e) {  
  19.             var keyCode = (e.which) ? e.which : e.keyCode  
  20.             if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32) {  
  21.                 return true;  
  22.             } else {  
  23.                 return false;  
  24.             }  
  25.         }  
  26.     </script>  
  27.     <title></title>  
  28. </head>  
  29.   
  30. <body ng-controller="myController"> Select Category : <select ng-model="category" ng-change="ShowHideDiv(category)">  
  31. <option value="0">Select</option>  
  32. <option value="Add New">Add New</option>  
  33. <option ng-repeat="item in CategoryList" value="{{item.Id}}">{{item.CatName}}</option>  
  34. </select> <br /> <br />  
  35.     <div ng-show="cat"> Category Name : <input type="text" ng-model="catName" id="txtCategory" onkeypress="return ValidateCatName(event);" /> </div> <br />  
  36.     <div ng-show="subcat"> SubCategory Name : <input type="text" ng-model="subCatName" id="txtSubCategory" onkeypress="return ValidateSubCatName(event);" /> <br /> <br /> Select Image : <input type="file" id="filebutton" files-input ng-model="file"> <br /> <br /> </div> <br /> <input type="submit" value="Submit" ng-click="InsertData(category,catName,subCatName,file)" ng-show="sumbmitbutton" /> <input type="button" value="Update" ng-click="UpdateData(category,subCatName,SubCatId,file)" ng-show="showEditUpdate" /> <input type="button" value="Cancel" ng-click="CancelUpdate()" ng-show="showEditUpdate" /> <br /> <br />  
  37.     <div ng-show="showGrid">  
  38.         <table border="1">  
  39.             <tr>  
  40.                 <th ng-show="false">SubCatId</th>  
  41.                 <th>CatName</th>  
  42.                 <th>SubCatName</th>  
  43.                 <th>Path</th>  
  44.                 <th>Action</th>  
  45.             </tr>  
  46.             <tr ng-repeat="cat in categoryDetails">  
  47.                 <td ng-show="false">{{cat.SubCatId}}</td>  
  48.                 <td>{{cat.CatName}}</td>  
  49.                 <td>{{cat.SubCatName}}</td>  
  50.                 <td><img ng-src="{{'Images' + '/' + cat.ImgPath}}" style="width:20px;height:20px;" /></td>  
  51.                 <td> <input type="button" value="Edit" ng-click="EditSubCat(cat.SubCatId)" /> <input type="button" value="Delete" ng-click="DeleteData(cat.SubCatId)" /> </td>  
  52.             </tr>  
  53.         </table>  
  54.     </div> <br /> <a href="EditCategory.html">Edit Category</a> </body>  
  55.   
  56. </html>  
Now first I have added reference of script angular.min.js,jquery-1.8.2.min.js,And javascript file which we have created which is Javascript19.js it is stored inside scripts folder in application.The script src will be the path of scripts which you have stored in your application.

The next two function are ValidateCatName and ValidateSubCatName which not allow user to enter numeric values for category name and subcategory name.This functions will be called on keypress event of category and subcategory textbox to the ng-app and ng-controller directive I have attached controller name and module name, Then there is category dropdown on its change event I have called ShowHideDiv method using ng-change directive.I have binded category selected by user to category property using ng-model directive.Then I have binded the list of category there Id as value and name using ng-repeat directive.CategoryList is the property which has been assign value in catList function on Js file.

There are two div one which contain category textbox and second contain subcategory textbox and fileupload control respectively which are not displayed initially and displayed depending upon value of category selected by user.I have used ng-show directive to show hide div
Then there are three buttons submit,update,cancel which will be displayed according to the value selected by user and respective functions will be called.I have used ng-click directive to call a function when user clicks on these buttons.

Then there is table inside a div.This div will be displayed if records are present otherwise it will not be displayed,so i have used ng-show directive to that showGrid property is attached initially it is set to false.The table also contains two button Edit and Delete to edit and delete data respectively.

Then there is a link provided to user to edit category on clicking this link user will be directed to EditCategory page.For this anchor tag is used.

Now right click on application and add a new js file give a name to it.I have given name as EditCat which is used to update,delete category and write following code on it.
  1. /// <reference path="Scripts/angular.min.js" />  
  2. /// <reference path="Scripts/jquery-1.8.2.min.js" />  
  3. var myApp = angular.module("myModule", []).controller("myController"function($scope, $http) {  
  4.     $scope.myValue = false;  
  5.     $scope.showHide = false;  
  6.     $scope.Id = "0";  
  7.     ViewData();  
  8.   
  9.     function ViewData() {  
  10.         $http({  
  11.             method: 'Get',  
  12.             url: 'WebService3.asmx/GetCategory'  
  13.         }).then(function(response) {  
  14.             if (response.data.length > 0) {  
  15.                 $scope.Category = response.data;  
  16.                 $scope.myValue = true;  
  17.             } else {  
  18.                 $scope.myValue = false;  
  19.             }  
  20.         })  
  21.     }  
  22.     $scope.DeleteData = function(Id) {  
  23.         if (window.confirm("Are you sure you want to Delete this record?")) $scope.result = "Yes";  
  24.         else $scope.result = "No";  
  25.         if ($scope.result == "Yes") {  
  26.             $http({  
  27.                 method: 'Post',  
  28.                 url: 'WebService3.asmx/DeleteCat',  
  29.                 data: "{'Id' : '" + Id + "'}",  
  30.                 contentType: "application/json; charset=utf-8",  
  31.                 dataType: "json"  
  32.             }).then(function(response) {  
  33.                 if (response.data.d > 0) {  
  34.                     alert("Record Deleted Successfully");  
  35.                     ViewData();  
  36.                 } else {  
  37.                     alert("Record Not Deleted");  
  38.                     ViewData();  
  39.                 }  
  40.             })  
  41.         }  
  42.     }  
  43.     $scope.EditData = function(Id) {  
  44.         $http({  
  45.             method: 'Post',  
  46.             url: 'WebService3.asmx/GetCatById',  
  47.             data: "{'Id' : '" + Id + "'}",  
  48.             contentType: "application/json; charset=utf-8",  
  49.             dataType: "json"  
  50.         }).then(function(response) {  
  51.             if (response.data.d.length > 0) {  
  52.                 var Result = jQuery.parseJSON(response.data.d);  
  53.                 $scope.Id = Result.Id;  
  54.                 $scope.CatName = Result.CatName;  
  55.                 $scope.showHide = true;  
  56.             }  
  57.         })  
  58.     }  
  59.     $scope.CancelUpdate = function() {  
  60.         clear();  
  61.     }  
  62.     $scope.UpdateData = function(Id, CatName) {  
  63.         if (CatName == "" || CatName == undefined) {  
  64.             alert("Please Enter Category Name")  
  65.         } else {  
  66.             $http({  
  67.                 method: 'Post',  
  68.                 url: 'WebService3.asmx/UpdateCat',  
  69.                 data: "{'Id' : '" + Id + "','CatName' : '" + CatName + "'}",  
  70.                 contentType: "application/json; charset=utf-8",  
  71.                 dataType: "json"  
  72.             }).then(function(response) {  
  73.                 clear();  
  74.                 if (response.data.d > 0) {  
  75.                     alert("Record Updated Successfully");  
  76.                     ViewData();  
  77.                 } else {  
  78.                     alert("Record Not Updated");  
  79.                     ViewData();  
  80.                 }  
  81.             })  
  82.         }  
  83.     }  
  84.   
  85.     function clear() {  
  86.         $scope.CatName = "";  
  87.         $scope.Id = "0";  
  88.         $scope.showHide = false;  
  89.     }  
  90. })  
In this also first add reference of two scripts angular.min.js and jquery-1.8.2.min.js which are already downloaded and order is important.
Here there are 3 properties assign to $scope object myValue,showHide set to false this will be set to true when user clicks on edit button and showHide will be set to true when list of cateogry is displayed to user inside grid and Id set to 0 which is catId initially set to zero.

To the controller $http is passed which is used to call webservice methods.

Then first function is ViewData which is used to fetch list of categories present and displayed to user on page Load
  • DeleteData function is used to delete the category
  • EditData is used to edit category base upon category Id
  • CancelUpdate if user wants to cancel category updation
  • UpdateData is used to update category name
  • Clear is used to reset values when user updates catName
Now right click on application and add an html page name it as EditCategory.html and write following code in it
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml" ng-app="myModule">  
  3.   
  4. <head>  
  5.     <script src="Scripts/angular.min.js" type="text/javascript" lang="ja"></script>  
  6.     <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript" lang="ja"></script>  
  7.     <script src="EditCat.js" type="text/javascript" lang="ja"></script>  
  8.     <script type="text/javascript" lang="ja">  
  9.         function ValidateCatName(e) {  
  10.             var keyCode = (e.which) ? e.which : e.keyCode  
  11.             if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32) {  
  12.                 return true;  
  13.             } else {  
  14.                 return false;  
  15.             }  
  16.         }  
  17.     </script>  
  18.     <title></title>  
  19. </head>  
  20.   
  21. <body ng-controller="myController">  
  22.     <div ng-show="showHide"> Category Name : <input type="text" ng-model="CatName" onkeypress="return ValidateCatName(event);" /> <br /> <input type="button" value="Update" ng-click="UpdateData(Id,CatName)" /> <input type="button" value="Cancel" ng-click="CancelUpdate()" /> </div>  
  23.     <div ng-show="myValue">  
  24.         <table border="1">  
  25.             <tr>  
  26.                 <th ng-show="false">Id</th>  
  27.                 <th>Name</th>  
  28.                 <th>Action</th>  
  29.             </tr>  
  30.             <tr ng-repeat="cat in Category">  
  31.                 <td ng-show="false">{{cat.Id}}</td>  
  32.                 <td>{{cat.CatName}}</td>  
  33.                 <td> <input type="button" value="Edit" ng-click="EditData(cat.Id)" /> <input type="button" value="Delete" ng-click="DeleteData(cat.Id)" /> </td>  
  34.             </tr>  
  35.         </table>  
  36.     </div> <a href="HtmlPage42.html">Back to List of SubCategory</a> </body>  
  37.   
  38. </html>  
First add reference of script files angular.min.js,jquery-1.8.2.min.js and EditCat.js which is been created just now.

Then there is function ValidateCatName which will not allow user to enter numeric values for category name and called on keypress event of catName textbox

Next there is a div which contains catName textbox which is initially not visible and will be visible when user clicks edit button.The div also contains Update and Cancel button to update catName or Cancel the updation respectively.

Then there is another div which is also not visible initially it will be visible if catName are present and respective category Name will be displayed in table inside the div.In the table there is edit and delete button to edit and delete category respectively.

Then a anchor tag is used on clicking this user can go back to main page from where category and subcategory can be added. Build and run the application by setting the page for Adding category and subcategory which is HtmlPage42 in my application as a startup page.