We create web service and method for CRUD operation.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Services;
- using System.Data;
- using System.Data.SqlClient;
- using System.Web.Configuration;
-
-
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
-
- [System.Web.Script.Services.ScriptService]
- public class hr_webservice : System.Web.Services.WebService
- {
- // getting connection string
- string conStr = WebConfigurationManager.ConnectionStrings["TESTDB"].ConnectionString;
-
- //Method for Get Employee List
- [WebMethod]
- public string GetEmployeeDetails()
- {
- DataTable dt = new DataTable();
- using (SqlConnection conn = new SqlConnection(conStr))
- {
- string sql = string.Format(@"Select * from [SampleInfoTable]");
- SqlDataAdapter da = new SqlDataAdapter(sql, conn);
- da.Fill(dt);
- }
- //var lst = dt.AsEnumerable().ToList();
- var lst = dt.AsEnumerable()
- .Select(r => r.Table.Columns.Cast<DataColumn>()
- .Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal])
- ).ToDictionary(z => z.Key, z => z.Value)
- ).ToList();
-
- //now serialize it
- var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
- return serializer.Serialize(lst);
- }
-
- // Method For Delete
- [WebMethod]
- public string DeleteEmployeeData(string employeeId)
- {
- int rowsInserted = 0;
- using (SqlConnection conn = new SqlConnection(conStr))
- {
- // Creating insert statement
- string sql = string.Format(@"Delete [SampleInfoTable] WHERE id='" + employeeId + "'");
- SqlCommand cmd = new SqlCommand(sql, conn);
- cmd.Connection = conn;
- cmd.CommandText = sql;
- cmd.CommandType = CommandType.Text;
- conn.Open();
- rowsInserted = cmd.ExecuteNonQuery();
- conn.Close();
- cmd = null;
- }
- return GetEmployeeDetails();
-
- }
-
- // Edit Employee Data
- [WebMethod]
- public string EditEmployeeData(string employeeId, string editedName, string editedEmail, string editedPhone, string editedAddress, string action_mode)
- {
- int rowsInserted = 0;
- // Creating Sql Connection
- using (SqlConnection conn = new SqlConnection(conStr))
- {
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = conn;
- cmd.CommandText = "sp_sample_info";
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.Add("@id", employeeId);
- cmd.Parameters.Add("@Name", editedName);
- cmd.Parameters.Add("@Email", editedEmail);
- cmd.Parameters.Add("@Phone", editedPhone);
- cmd.Parameters.Add("@Address", editedAddress);
- cmd.Parameters.Add("@Action", action_mode);
-
-
- conn.Open();
- rowsInserted = cmd.ExecuteNonQuery();
- conn.Close();
- cmd = null;
- }
-
- return GetEmployeeDetails();
-
- }
- }
This is HTML page where we are calling web service with JSON format.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <style type="text/css">
- .tableStyle
- {
- background-color: White;
- border: 1px solid rgb(204, 204, 204);
- font-family: Tahoma;
- font-size: 14px;
- width: 1000px;
- border-collapse: collapse;
- }
-
- .tableHeader
- {
- color: White;
- height: 30px;
- background-color: rgb(15, 159, 15);
- font-weight: bold;
- }
-
- .tableRaw
- {
- border: 1px solid rgb(204, 204, 204);
- }
-
- input.button
- {
- font: bold 12px Arial, Sans-serif;
- height: 24px;
- margin: 0;
- padding: 2px 3px;
- color: black;
- border: none;
- }
- </style>
-
- <script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
-
- <script type="text/javascript">
-
- $(document).ready(function () {
- GetEmployeeDetails();
- });
-
- function GetEmployeeDetails() { // This is select method for JSON
- $.ajax({
- type: "POST",
- url: "hr_webservice.asmx/GetEmployeeDetails",
- data: "{}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- BindTable(JSON.parse(response.d));
- },
- failure: function (msg) {
- alert(msg);
- }
- });
- }
-
- function BlankValidation(editedName, editedEmail, editedPhone, editedAddress) { // Validation check before insert
-
- if (editedName == '') {
- alert('Blank is not allow');
- editedName.focus();
- returnVal = false;
- return returnVal;
- }
- else if (editedEmail == '') {
- alert('Blank is not allow');
- editedEmail.focus();
- returnVal = false;
- return returnVal;
- }
- else if (editedPhone == '') {
- alert('Blank is not allow');
- editedPhone.focus();
- returnVal = false;
- return returnVal;
- }
- else if (editedAddress == '') {
- alert('Blank is not allow');
- editedAddress.focus();
- returnVal = false;
- return returnVal;
- }
- var returnVal = true;
- return returnVal;
- }
-
- function EditEmployeeData() { // Edit Employee Data
-
- var editedName = $('#txEditedName').val();
- var editedEmail = $('#txEditedEmail').val();
- var editedPhone = $('#txEditedPhone').val();
- var editedAddress = $('#txEditedAddress').val();
- var hfEditedId = $('#hfEditedId').val();
- var hfActionMode = $('#hfActionMode').val();
-
- // Blank validation check
- if (BlankValidation(editedName, editedEmail, editedPhone, editedAddress) == true) {
-
- // call ajax JSON method
- $.ajax({
- type: "POST",
- url: "hr_webservice.asmx/EditEmployeeData",
- data: "{ 'employeeId': '" + hfEditedId
- + "','editedName': '" + editedName
- + "', 'editedEmail': '" + editedEmail
- + "','editedPhone':'" + editedPhone
- + "','editedAddress':'" + editedAddress
- + "','action_mode':'" + hfActionMode + "'}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- BindTable(JSON.parse(response.d));
- },
- failure: function (msg) {
- alert(msg);
- }
- });
- ResetText();
- }
- }
-
- function ResetText() { // Method for Reset Control
- var editedName = $('#txEditedName').val('');
- var editedEmail = $('#txEditedEmail').val('');
- var editedPhone = $('#txEditedPhone').val('');
- var editedAddress = $('#txEditedAddress').val('');
- var hfEditedId = $('#hfEditedId').val('');
- var hfActionMode = $('#hfActionMode').val('NEW');
- var btnEntry = $('#btnEntry').val('New Entry');
- }
-
- function EditMode(empId, empName, empEmail, empPhone, empAddress) {
-
- var hfEditedId = $('#hfEditedId').val(empId);
- var txEditedName = $('#txEditedName').val(empName);
- var txEditedEmail = $('#txEditedEmail').val(empEmail);
- var txEditedPhone = $('#txEditedPhone').val(empPhone);
- var txEditedAddress = $('#txEditedAddress').val(empAddress);
- var hfActionMode = $('#hfActionMode').val('UPDATE');
- var btnEntry = $('#btnEntry').val('Update');
- }
-
- function DeleteMode(deleteEmpId) {
-
- var agree = confirm("Are you sure you want to delete this information ?");
- if (agree) {
- $.ajax({
- type: "POST",
- url: "hr_webservice.asmx/DeleteEmployeeData",
- data: "{ 'employeeId': '" + deleteEmpId + "'}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- BindTable(JSON.parse(response.d));
- },
- failure: function (msg) {
- alert(msg);
- }
- });
- }
- }
-
- function BindTable(Employees) {
-
- var root = document.getElementById('mydiv');
- try {
- var tblId = document.getElementById('tblGridValue');
- if (tblId != null) {
- root.removeChild(tblId);
- }
- }
- catch (e) {
-
- }
- var tab = document.createElement('table');
- tab.setAttribute("id", "tblGridValue");
- tab.setAttribute("class", "tableStyle");
- tab.setAttribute("cellspacing", "3px");
- var tbo = document.createElement('tbody');
- var row, cell;
- // the list object now extract the value for each row
- $.each(Employees, function (index, employee) {
- row = document.createElement('tr');
- row.setAttribute("class", "tableRaw");
-
-
- // the object of LIST is now extract the each cell of row
-
- for (var j = 0; j < 5; j++) {
- cell = document.createElement('td');
- cell.setAttribute("width", "200px");
- var empId = employee.id;
- var empName = employee.Name;
- var empEmail = employee.Email;
- var empPhone = employee.Phone;
- var empAddress = employee.Address;
- if (j == 0) {
-
- //Create an input type dynamically.
- var hiddenId = document.createElement("input");
- //Assign different attributes to the element.
- hiddenId.setAttribute("type", "hidden");
- hiddenId.setAttribute("id", "hfRow_" + employee.Id);
- hiddenId.setAttribute("value", employee.Id);
- cell.appendChild(hiddenId);
- cell.appendChild(document.createTextNode(employee.Name));
- }
- else if (j == 1) {
- var spanValue = document.createElement("span");
- cell.setAttribute("width", "200px");
- spanValue.setAttribute("display", "inline-block");
- spanValue.appendChild(document.createTextNode(employee.Email));
- cell.appendChild(spanValue);
- }
- else if (j == 2) {
- cell.setAttribute("width", "200px");
- cell.appendChild(document.createTextNode(employee.Phone));
- }
- else if (j == 3) {
- cell.setAttribute("width", "200px");
- cell.appendChild(document.createTextNode(employee.Address));
- }
- else if (j == 4) {
-
- // in this state loop generates Edit and Delete button for each row
- //
- var element = document.createElement("img");
- element.setAttribute("src", "images/edit-icon.gif");
- element.setAttribute("width", "15px");
- cell.setAttribute("width", "100px");
-
-
- // This loop also adding a click event EditMode()
- element.setAttribute("onclick", "EditMode('"
- + empId + "','"
- + empName + "','"
- + empEmail + "','"
- + empPhone + "','"
- + empAddress + "')");
-
- cell.appendChild(element);
-
-
- // Same way the row created Delete button
- var elementDelete = document.createElement("img");
- elementDelete.setAttribute("src", "images/DeleteRed.png");
- elementDelete.setAttribute("width", "15px");
-
-
- // Also created the Delete Method in onclick event
- elementDelete.setAttribute("onclick", "return DeleteMode('" + empId + "')");
- cell.appendChild(elementDelete);
- }
- row.appendChild(cell);
- }
- tbo.appendChild(row);
- });
- tab.appendChild(tbo);
- root.appendChild(tab);
- }
-
- </script>
- </head>
-
-
- <body style="background-color: #cccccc;">
- <form id="form1" runat="server">
-
- <div style="float: left; background-color: White; width: 1050px;">
-
- <div style="background-color: White">
- <h3>Sample Task Grid (Add/Edit/Update/Delete)Using web Service with JSON</h3>
- </div>
- <div style="width: 1000px; background-color: White;">
-
- <table class="tableStyle" width="1000px">
-
- <tr style="border: 1px solid black;">
-
- <td style="width: 200px">
- <asp:HiddenField ID="hfEditedId" runat="server" />
- <asp:HiddenField ID="hfActionMode" Value="NEW" runat="server" />
- <input id="txEditedName" type="text" name="name" value=" " style="width: 98%" />
- </td>
-
- <td style="width: 200px">
- <input id="txEditedEmail" type="text" name="name" value=" " style="width: 98%" />
- </td>
-
- <td style="width: 200px">
- <input id="txEditedPhone" type="text" name="name" value=" " style="width: 98%" />
- </td>
-
- <td style="width: 200px">
- <input id="txEditedAddress" type="text" name="name" value=" " style="width: 98%" />
- </td>
-
- <td style="width: 100px; padding-left: 10px;">
- <div style="padding-bottom: 5px">
- <input id="btnEntry" type="button" class="button" name="editAjaxGrid" value="New Entry" style="width: 80px" onclick="EditEmployeeData()" />
- </div>
-
- <div style="padding-bottom: 5px">
- <input id="Button1" type="button" class="button" name="reset" value="Reset" style="width: 80px" onclick=" ResetText()" />
- </div>
- </td>
- </tr>
-
-
- <tr class="tableHeader">
- <td style="width: 200px">Name</td>
- <td style="width: 200px">Email Address</td>
- <td style="width: 200px">Mobile Number</td>
- <td style="width: 200px">Address</td>
- <td style="width: 100px; padding-left: 10px;">Action</td>
- </tr>
-
- </table>
-
- <div id="mydiv"></div>
- </div>
- </div>
- </form>
- </body>
- </html>
CRUD Oparetion using web service.
Find database script attached.