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. CREATE PROCEDURE Insert_delete_update_subcat (@Para VARCHAR(50)='',
  54. @SubCatId INT = 0,
  55. @CatId INT = 0,
  56. @CatName VARCHAR(50) = '',
  57. @SubCatName VARCHAR(50) = '',
  58. @imgPath VARCHAR(50) = '',
  59. @IsActive BIT = 0)
  60. AS
  61. BEGIN
  62. IF @Para = 'Add'
  63. BEGIN
  64. IF Len(@CatName) > 0
  65. BEGIN
  66. EXEC Insert_update_delete_category
  67. 'Add',
  68. 0,
  69. @CatName,
  70. 1
  71. SELECT @CatId = Max(catid)
  72. FROM tblcat
  73. INSERT INTO tblsubcat
  74. (catid,
  75. subcatname,
  76. imgpath,
  77. isactive)
  78. VALUES (@CatId,
  79. @SubCatName,
  80. @imgPath,
  81. 1)
  82. END
  83. ELSE
  84. BEGIN
  85. INSERT INTO tblsubcat
  86. (catid,
  87. subcatname,
  88. imgpath,
  89. isactive)
  90. VALUES (@CatId,
  91. @SubCatName,
  92. @imgPath,
  93. 1)
  94. END
  95. END
  96. ELSE IF @Para = 'GetCat'
  97. BEGIN
  98. SELECT catid,
  99. catname
  100. FROM tblcat
  101. WHERE isactive = 1
  102. END
  103. ELSE IF @Para = 'GetForGrid'
  104. BEGIN
  105. SELECT S.subcatid,
  106. C.catname,
  107. S.subcatname,
  108. S.imgpath
  109. FROM tblcat C
  110. JOIN tblsubcat S
  111. ON C.catid = S.catid
  112. WHERE S.isactive = 1
  113. AND C.isactive = 1
  114. END
  115. ELSE IF @Para = 'GetById'
  116. BEGIN
  117. SELECT C.catid,
  118. C.catname,
  119. S.subcatid,
  120. imgpath,
  121. S.subcatname
  122. FROM tblsubcat S
  123. JOIN tblcat C
  124. ON C.catid = S.catid
  125. WHERE subcatid = @SubCatId
  126. AND S.isactive = 1
  127. END
  128. ELSE IF @Para = 'Update'
  129. BEGIN
  130. UPDATE tblsubcat
  131. SET subcatname = @SubCatName,
  132. imgpath = @imgPath,
  133. isactive = 1
  134. WHERE catid = @CatId
  135. AND subcatid = @SubCatId
  136. END
  137. ELSE IF @Para = 'GetByCatId'
  138. BEGIN
  139. SELECT S.subcatid,
  140. C.catname,
  141. S.subcatname,
  142. S.imgpath
  143. FROM tblcat C
  144. JOIN tblsubcat S
  145. ON C.catid = S.catid
  146. WHERE S.isactive = 1
  147. AND C.isactive = 1
  148. AND S.catid = @CatId
  149. END
  150. ELSE IF @Para = 'Delete'
  151. BEGIN
  152. UPDATE tblsubcat
  153. SET isactive = 0
  154. WHERE subcatid = @SubCatId
  155. END
  156. 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. function clear() {
  101. $scope.catName = '';
  102. $('#txtCategory').val('');
  103. $scope.subCatName = '';
  104. $('#txtSubCategory').val('');
  105. $scope.file = '';
  106. $("#filebutton").val('');
  107. $scope.category = "0";
  108. $scope.cat = false;
  109. $scope.subcat = false;
  110. $scope.sumbmitbutton = false;
  111. $scope.showEditUpdate = false;
  112. }
  113. function GetAllRecords() {
  114. $http({
  115. method: 'Get',
  116. url: 'WebService3.asmx/GetAllDetails'
  117. }).then(function(response) {
  118. if (response.data.length > 0) {
  119. $scope.categoryDetails = response.data;
  120. $scope.showGrid = true;
  121. }
  122. })
  123. }
  124. $scope.EditSubCat = function(Id) {
  125. $http({
  126. method: 'Post',
  127. url: 'WebService3.asmx/GetById',
  128. data: "{'Id' : '" + Id + "'}",
  129. contentType: "application/json; charset=utf-8",
  130. dataType: "json"
  131. }).then(function(response) {
  132. if (response.data.d.length > 0) {
  133. var Result = jQuery.parseJSON(response.data.d);
  134. $scope.SubCatId = Result.SubCatId;
  135. $scope.subCatName = Result.SubCatName;
  136. $scope.category = Result.CatId;
  137. $scope.file = '';
  138. $("#filebutton").val('');
  139. $scope.subcat = true;
  140. $scope.cat = false;
  141. $scope.sumbmitbutton = false;
  142. $scope.showEditUpdate = true;
  143. }
  144. })
  145. }
  146. $scope.UpdateData = function(category, subCatName, SubCatId, file) {
  147. var FileName = "";
  148. var msg = "";
  149. if (category == "0" || category == undefined) {
  150. msg += "Please Select Category, ";
  151. }
  152. if (subCatName == '' || subCatName == undefined) {
  153. msg += "Please Enter SubCategory Name, ";
  154. }
  155. if (file == '' || file == undefined) {
  156. msg += "Please Select Image, ";
  157. }
  158. if (msg.length > 0) {
  159. msg = msg.substring(0, msg.length - 2);
  160. alert(msg);
  161. } else {
  162. var Cat = category;
  163. var CatName = "";
  164. var SubCatName = subCatName;
  165. var SubCatId = SubCatId;
  166. FileName = file[0].name;
  167. UploadFile(Cat, CatName, SubCatName, FileName, SubCatId);
  168. }
  169. }
  170. $scope.CancelUpdate = function() {
  171. clear();
  172. GetAllRecords();
  173. }
  174. $scope.DeleteData = function(SubCatId) {
  175. if (window.confirm("Are you sure you want to Delete this record?")) $scope.result = "Yes";
  176. else $scope.result = "No";
  177. if ($scope.result == "Yes") {
  178. $http({
  179. method: 'Post',
  180. url: 'WebService3.asmx/DeleteSubCat',
  181. data: "{'Id' : '" + SubCatId + "'}",
  182. contentType: "application/json; charset=utf-8",
  183. dataType: "json"
  184. }).then(function(response) {
  185. clear();
  186. if (response.data.d > 0) {
  187. alert("Record Deleted Successfully");
  188. GetAllRecords();
  189. } else {
  190. alert("Record Not Deleted");
  191. GetAllRecords();
  192. }
  193. })
  194. }
  195. }
  196. function UploadFile(Cat, CatName, SubCatName, FileName, SubCatId) {
  197. var fileUpload = $('#filebutton').get(0);
  198. $log.info(fileUpload);
  199. var files = fileUpload.files;
  200. $log.info(files);
  201. var test = new FormData();
  202. for (var i = 0; i < files.length; i++) {
  203. test.append(files[i].name, files[i]);
  204. $log.info(test);
  205. }
  206. $.ajax({
  207. url: "Handler1.ashx",
  208. type: "POST",
  209. contentType: false,
  210. processData: false,
  211. data: test,
  212. success: function(result) {
  213. if (result == "File Uploaded Successfully!") {
  214. if ($scope.sumbmitbutton == true) {
  215. $http({
  216. method: 'Post',
  217. url: 'WebService3.asmx/InsertCat',
  218. data: "{'Category' : '" + Cat + "','CatName' : '" + CatName + "','SubCatName' : '" + SubCatName + "','File' : '" + FileName + "'}",
  219. contentType: "application/json; charset=utf-8",
  220. dataType: "json"
  221. }).then(function(response) {
  222. clear();
  223. if (response.data.d > 0) {
  224. alert("Record Inserted Successfully");
  225. $scope.catList();
  226. GetAllRecords();
  227. } else {
  228. alert("Entry Already Exists");
  229. $scope.catList();
  230. GetAllRecords();
  231. }
  232. })
  233. }
  234. if ($scope.showEditUpdate == true) {
  235. $http({
  236. method: 'Post',
  237. url: 'WebService3.asmx/UpdateSubCat',
  238. data: "{'Category' : '" + Cat + "','SubCatName' : '" + SubCatName + "','subCatId' : '" + SubCatId + "','File' : '" + FileName + "'}",
  239. contentType: "application/json; charset=utf-8",
  240. dataType: "json"
  241. }).then(function(response) {
  242. clear();
  243. if (response.data.d > 0) {
  244. alert("Record Updated Successfully");
  245. $scope.catList();
  246. GetAllRecords();
  247. } else {
  248. alert("Record Not Updated Successfully");
  249. $scope.catList();
  250. GetAllRecords();
  251. }
  252. })
  253. }
  254. } else {
  255. alert(result);
  256. $scope.file = '';
  257. $("#filebutton").val('');
  258. }
  259. }
  260. });
  261. }
  262. })
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. <head>
  4. <script src="Scripts/angular.min.js" type="text/javascript" lang="ja"></script>
  5. <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript" lang="ja"></script>
  6. <script src="Scripts/JavaScript19.js" type="text/javascript" lang="ja"></script>
  7. <script type="text/javascript" lang="ja">
  8. function ValidateCatName(e) {
  9. var keyCode = (e.which) ? e.which : e.keyCode
  10. if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32) {
  11. return true;
  12. } else {
  13. return false;
  14. }
  15. }
  16. function ValidateSubCatName(e) {
  17. var keyCode = (e.which) ? e.which : e.keyCode
  18. if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32) {
  19. return true;
  20. } else {
  21. return false;
  22. }
  23. }
  24. </script>
  25. <title></title>
  26. </head>
  27. <body ng-controller="myController"> Select Category : <select ng-model="category" ng-change="ShowHideDiv(category)">
  28. <option value="0">Select</option>
  29. <option value="Add New">Add New</option>
  30. <option ng-repeat="item in CategoryList" value="{{item.Id}}">{{item.CatName}}</option>
  31. </select> <br /> <br />
  32. <div ng-show="cat"> Category Name : <input type="text" ng-model="catName" id="txtCategory" onkeypress="return ValidateCatName(event);" /> </div> <br />
  33. <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 />
  34. <div ng-show="showGrid">
  35. <table border="1">
  36. <tr>
  37. <th ng-show="false">SubCatId</th>
  38. <th>CatName</th>
  39. <th>SubCatName</th>
  40. <th>Path</th>
  41. <th>Action</th>
  42. </tr>
  43. <tr ng-repeat="cat in categoryDetails">
  44. <td ng-show="false">{{cat.SubCatId}}</td>
  45. <td>{{cat.CatName}}</td>
  46. <td>{{cat.SubCatName}}</td>
  47. <td><img ng-src="{{'Images' + '/' + cat.ImgPath}}" style="width:20px;height:20px;" /></td>
  48. <td> <input type="button" value="Edit" ng-click="EditSubCat(cat.SubCatId)" /> <input type="button" value="Delete" ng-click="DeleteData(cat.SubCatId)" /> </td>
  49. </tr>
  50. </table>
  51. </div> <br /> <a href="EditCategory.html">Edit Category</a> </body>
  52. </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. function ViewData() {
  9. $http({
  10. method: 'Get',
  11. url: 'WebService3.asmx/GetCategory'
  12. }).then(function(response) {
  13. if (response.data.length > 0) {
  14. $scope.Category = response.data;
  15. $scope.myValue = true;
  16. } else {
  17. $scope.myValue = false;
  18. }
  19. })
  20. }
  21. $scope.DeleteData = function(Id) {
  22. if (window.confirm("Are you sure you want to Delete this record?")) $scope.result = "Yes";
  23. else $scope.result = "No";
  24. if ($scope.result == "Yes") {
  25. $http({
  26. method: 'Post',
  27. url: 'WebService3.asmx/DeleteCat',
  28. data: "{'Id' : '" + Id + "'}",
  29. contentType: "application/json; charset=utf-8",
  30. dataType: "json"
  31. }).then(function(response) {
  32. if (response.data.d > 0) {
  33. alert("Record Deleted Successfully");
  34. ViewData();
  35. } else {
  36. alert("Record Not Deleted");
  37. ViewData();
  38. }
  39. })
  40. }
  41. }
  42. $scope.EditData = function(Id) {
  43. $http({
  44. method: 'Post',
  45. url: 'WebService3.asmx/GetCatById',
  46. data: "{'Id' : '" + Id + "'}",
  47. contentType: "application/json; charset=utf-8",
  48. dataType: "json"
  49. }).then(function(response) {
  50. if (response.data.d.length > 0) {
  51. var Result = jQuery.parseJSON(response.data.d);
  52. $scope.Id = Result.Id;
  53. $scope.CatName = Result.CatName;
  54. $scope.showHide = true;
  55. }
  56. })
  57. }
  58. $scope.CancelUpdate = function() {
  59. clear();
  60. }
  61. $scope.UpdateData = function(Id, CatName) {
  62. if (CatName == "" || CatName == undefined) {
  63. alert("Please Enter Category Name")
  64. } else {
  65. $http({
  66. method: 'Post',
  67. url: 'WebService3.asmx/UpdateCat',
  68. data: "{'Id' : '" + Id + "','CatName' : '" + CatName + "'}",
  69. contentType: "application/json; charset=utf-8",
  70. dataType: "json"
  71. }).then(function(response) {
  72. clear();
  73. if (response.data.d > 0) {
  74. alert("Record Updated Successfully");
  75. ViewData();
  76. } else {
  77. alert("Record Not Updated");
  78. ViewData();
  79. }
  80. })
  81. }
  82. }
  83. function clear() {
  84. $scope.CatName = "";
  85. $scope.Id = "0";
  86. $scope.showHide = false;
  87. }
  88. })
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. <head>
  4. <script src="Scripts/angular.min.js" type="text/javascript" lang="ja"></script>
  5. <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript" lang="ja"></script>
  6. <script src="EditCat.js" type="text/javascript" lang="ja"></script>
  7. <script type="text/javascript" lang="ja">
  8. function ValidateCatName(e) {
  9. var keyCode = (e.which) ? e.which : e.keyCode
  10. if (((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122)) || keyCode == 32) {
  11. return true;
  12. } else {
  13. return false;
  14. }
  15. }
  16. </script>
  17. <title></title>
  18. </head>
  19. <body ng-controller="myController">
  20. <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>
  21. <div ng-show="myValue">
  22. <table border="1">
  23. <tr>
  24. <th ng-show="false">Id</th>
  25. <th>Name</th>
  26. <th>Action</th>
  27. </tr>
  28. <tr ng-repeat="cat in Category">
  29. <td ng-show="false">{{cat.Id}}</td>
  30. <td>{{cat.CatName}}</td>
  31. <td> <input type="button" value="Edit" ng-click="EditData(cat.Id)" /> <input type="button" value="Delete" ng-click="DeleteData(cat.Id)" /> </td>
  32. </tr>
  33. </table>
  34. </div> <a href="HtmlPage42.html">Back to List of SubCategory</a> </body>
  35. </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.