Sunday, 2 August 2015

Web Api -Get and Post Data From Client(Html) And Server(ASPX) Side

No comments
- First create new project as web api project
- First Edit WebConfig File To  Add AppSettings

WebConfig:

<configuration> 
  <appSettings>
    <add key="DataSource" value="TEST" />
    <add key="InitialCatalog" value="TestProject" />
    <add key="UserID" value="sa" />
    <add key="Password" value="sql2008" />
    <add key="ServerName" value="localhost" />
  </appSettings>
</configuration>

 - Create New Folder "MyHelperLib" and Add New Class File "APICommonUtil.cs"

APICommonUtil.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace D2D.WebAPI.MyHelperLib
{
    public class APICommonUtil
    {
        internal static string GetDBConnString()
        {
            SqlConnectionStringBuilder oSQLConnStr = new SqlConnectionStringBuilder();
            oSQLConnStr.DataSource = WebConfigurationManager.AppSettings["DataSource"].ToString();
            oSQLConnStr.InitialCatalog = WebConfigurationManager.AppSettings["InitialCatalog"].ToString();
            oSQLConnStr.UserID = WebConfigurationManager.AppSettings["UserID"].ToString();
            oSQLConnStr.Password = WebConfigurationManager.AppSettings["Password"].ToString();
            return oSQLConnStr.ToString();
        }
    }
}

- Add new Controller as TestController

TestController.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Http;
using System.Web.Routing;
using System.Web.Script.Serialization;

[RoutePrefix("api/test")]
public class UserController : ApiController
{
    #region "Connection String"
    string MyConnectionString = D2D.WebAPI.MyHelperLib.APICommonUtil.GetDBConnString();
    #endregion

    #region ''

    // GET api/<controller>
    public IEnumerable<string> GetValues()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5

    public string GetValue(int id)
    {
        return "value";
    }
    // POST api/<controller>
    public void PostValue([FromBody]string data)
    {

    }
    // PUT api/<controller>/5

    public void PutValue(int id, [FromBody]string data)
    {

    }
    // DELETE api/<controller>/5
    public void DeleteValue(int id)
    { }

    #endregion

    #region "Get"

 
    /**Get Method To Get Data**/

    [Route("UserInfo//{UserId}")]
    public DataSet GetRoleMenu(string UserId)
    {
        using (SqlConnection connection = new SqlConnection(MyConnectionString))
        {
            connection.Open();
            SqlCommand cmd = new SqlCommand("select * from UserInfo Where        UserId='"+UserId+"'", connection);       
            SqlDataAdapter adpt = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adpt.Fill(ds);
            ds.Tables[0].TableName = "Users";

            if (ds.Tables[0].Rows.Count == 0)
            {
                throw new Exception("Unable to find any User.");
            }
            else
            {
                return ds;
            }
        }
    }

    #endregion

    #region "POST api/<controller>"

    /*Post Method To Insert-Update User*/
  //With QueryString
    [HttpPost]
    [Route("UserInfo}")]
    public int SetUserInfo()
    {      
        NameValueCollection User= HttpUtility.ParseQueryString(Request.RequestUri.Query);
        SqlConnection connection = new SqlConnection(MyConnectionString);
        SqlCommand cmd = new SqlCommand("spAddUpdateUser", connection);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter adpt = new SqlDataAdapter(cmd);
        //string server = WebConfigurationManager.AppSettings["ServerName"].ToString();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@UserId", Item[0] == "" ? DBNull.Value.ToString() : User[0]);
        cmd.Parameters.AddWithValue("@UserName", Item[1] == "" ? DBNull.Value.ToString() : User[1]);   
        cmd.Connection = connection;
        int UserId= 0;
        try
        {
            connection.Open();
            UserId= (int)cmd.ExecuteScalar();
        }
        catch (Exception)
        { }
        finally
        {
            connection.Close();
        }
        return itemId;
    }
    #endregion
}

-  Create Wrapper.js File To Post And Get Data From Client Side i.e From HTML Page

Wrapper.jsvar APIWrapper = function (url) {

    var Priviliged = {
        myWebReqUrl: null,

        WebApiUriConstant: function () {
            try {
                var apiUri = "http://localhost/WebAPI/api";           
            } catch (e) {
                //alert(e.stack);
            }
            return apiUri;
        },

        CallWebAPI: function (webApiUrl, isAsync, myCallBackOnSuccess, myCallBackOnFailure) {

            var sData = "";
            try {
                $.ajax({
                    type: "GET",
                    url: webApiUrl,
                    data: sData,
                    async: isAsync,
                    contentType: "application/json;",
                    dataType: "json",
                    success: function (data) {
                        if (myCallBackOnSuccess != null); myCallBackOnSuccess(data);

                    },
                    error: function (xhr, status, error) {

                        var errorMessage = '';
                        try {
                            var xhr = JSON.parse(xhr.responseText);
                            errorMessage = xhr.ExceptionMessage;
                        } catch (e) {
                            errorMessage = "";
                        }

                        if (myCallBackOnFailure != null); myCallBackOnFailure(xhr.responseText);
                    }
                });
            }
            catch (e) {
                //alert(e.stack);
                //TODO - Display error message in popup screen.
            }
        },

        PostWebAPI: function (webApiUrl, isAsync, myCallBackOnSuccess, myCallBackOnFailure) {

            var sData = "";
            try {
                $.ajax({
                    type: "POST",
                    url: webApiUrl,
                    data: sData,
                    async: isAsync,
                    contentType: "application/json;",
                    dataType: "json",
                    sucess: function (data) {
                        if (myCallBackOnSuccess != null);
                        myCallBackOnSuccess(data);
                    },
                    error: function (xhr, satus, error) {
                        var errorMessage = "";
                        try {
                            var xhr = JSON.parse(xhr.responseText);
                            errorMessage = xhr.ExceptionMessage;
                        }
                        catch (e) {
                            errorMessage = "";
                        }
                        if (myCallBackOnFailure != null);
                        myCallBackOnFailure(xhr.responseText);
                    }
                });
            }
            catch (e) {
                //alert(e.stack);
                //TODO - Display error message in popup screen.
            }
        }
    };//End Priviliged


    var External = {

        /***** Start User Public function for the js  *****/

        InsertUser: function (UserDetail, myCallBackOnSuccess, myCallBackOnError) {
          Priviliged.myWebReqUrl = Priviliged.WebApiUriConstant() + "/UserInfo/?UserId=" + UserDetail.UserId+
                                                                                    "&UserName=" + UserDetail.UserName;
            Priviliged.PostD2DWebAPI(Priviliged.myWebReqUrl, false, callBackOnSuccess, callBackOnError)
        },      

        GetUser: function (UserId, callBackOnSuccess, callBackOnError) {
            Priviliged.myWebReqUrl = Priviliged.WebApiUriConstant() + "/UserInfo/" + UserId;
            Priviliged.CallD2DWebAPI(Priviliged.myWebReqUrl, true, callBackOnSuccess, callBackOnError)
        },
   }
}


-  Now Call This Wrapper.Js Function To HTML Page Where Data Is Sent

Test.html:


//
Insert User
 var BindUser= ({ UserId: $('#txtUser').val(), UserName: $('#txtUserName').val()});
APIWrapper.InsertUser(BindUser, function (objUser) {                 }, function () {
                    });

//GET User
APIWrapper.GetUser(hdnUserId,function (objUser) {
            try {
                if (objUser!= null && objUser!= undefined && objUser.Users.length > 0) {
//Bind DropDownList With Get Data
                    $.each(objUser.Users, function (index, item) {
                        $("#cmbUser").get(0).options[$("#cmbUser").get(0).options.length] = new Option(item.UserName, item.UserId);                  
                    });
                }
            }
            catch (e) {
            }
        }, function () {
        });
/********************** TO Get And Post Data From Server Side ********************/
- First create ApiCall.cs

ApiCall.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Helper
{
    public class ApiCall
    {
        private string JSON = "";

        //Get
        public string GetFromWebService(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            JSON = "";
            try
            {
                request.Timeout = 60000;
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    //System.Threading.Thread.Sleep(500);
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    JSON = value;
                    return value;
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }

        // POST a JSON string
        public string PostToWebService(string url, string jsonContent)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Timeout = 6000;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;
            request.ContentType = @"application/json";

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            long length = 0;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;
                    var value = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    JSON = value;
                    return JSON;
                    //JSONObject = response;
                }
            }
            catch (WebException ex)
            {
                // Log exception and throw as for GET example above
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }
    }
}
- Now Call ApiCall.cs Method From ASPX Code Behinde

Test.aspx
//To Post Data
protected void btnSave_Click(object sender, EventArgs e)
        {
            string URL_ADDRESS = String.Format("http://localhost/WebAPI/api/UserInfo/{0}/{1}", txtUserId.Text, txtUserName.Text);
            ApiCall objAPICall = new ApiCall();
            objAPICall.PostToWebService(URL_ADDRESS, "");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Clear", "clear()", true);  
        }

read more

Saturday, 1 August 2015

To Calculate Time Difference As HH:MM:SS With Today Date And Column Date

No comments

SELECT
 CAST(DATEDIFF(second, Dttm, getdate()) / 60 / 60 / 24 AS NVARCHAR(50)) + ':'+
     CAST(DATEDIFF(second, Dttm, getdate()) / 60 / 60 % 24  AS NVARCHAR(50)) + ':' +
     CAST(DATEDIFF(second, Dttm, getdate()) / 60 % 60 AS NVARCHAR(50)) as Hour
FROM YourTable
read more

Cursor To insert comma seprated value to table

No comments
SP :

CREATE PROCEDURE spCursor  
(
    @Name VARCHAR(250),   
)
AS
BEGIN
    DECLARE @lReturnCode INT
    DECLARE @lErrorCode INT
 
//declare temporary table
DECLARE @tempCursor Table (
        Name  Varchar(250)
        )

    SET NOCOUNT ON
    SELECT @lErrorCode = 0

//fnSplitIntoTable is function used to convert string to rows by seperating with commas 

BEGIN


    INSERT INTO @tempCursor
        SELECT  vcValuesList as 'CursorName' FROM fnSplitIntoTable(@Name ,',') 
   
        DECLARE @NameToPass VARCHAR(MAX)
        DECLARE cur4Name CURSOR FOR
        SELECT Name from @tempCursor

        OPEN   cur4Name

        FETCH NEXT FROM cur4Name INTO @NameToPass
         WHILE @@FETCH_STATUS = 0
            BEGIN
                SELECT @lReturnCode = 1                
                        BEGIN       
                            INSERT INTO YourTable(Name) VALUES (@NameToPass)
                        END
   
                    SELECT @lErrorCode = @@ERROR
                    IF @lErrorCode != 0 GOTO ErrorHandler
           
                     -- If we get here, no Error occurred
                    SELECT @lReturnCode = 0                 

                  --print @NameToPass
                 FETCH NEXT FROM cur4Name INTO @NameToPass
             END
             CLOSE cur4Name
             DEALLOCATE cur4Name
                        
    END
    -- On success, returns 0 as lReturnCode and inserted data
   
   
    -- Error Handler returns the return code

    ErrorHandler:

    SET NOCOUNT OFF

    SELECT 'lReturnCode'=@lReturnCode, 'lErrorCode'=@lErrorCode

    RETURN
END







Function To Split Comma To Rows :


CREATE FUNCTION [dbo].[fnSplitIntoTable] (@vcInString VARCHAR(MAX), @cDELIMITER CHAR(1))
RETURNS @OutTable TABLE (vcValuesList VARCHAR(255))
AS
BEGIN
DECLARE @pos INT
SET @vcInString = RTRIM(LTRIM(@vcInString))
SET @pos = CHARINDEX(@cDELIMITER,@vcInString,1)
WHILE @pos <> 0
BEGIN
INSERT INTO @OutTable
SELECT LTRIM(RTRIM(LEFT(@vcInString,@pos-1)))
SET @vcInString = SUBSTRING(@vcInString,@pos+1,LEN(@vcInString))
SET @pos = CHARINDEX(@cDELIMITER,@vcInString,1)
END
INSERT INTO @OutTable
SELECT RTRIM(LTRIM(@vcInString))
RETURN
END
 

read more

Tuesday, 14 April 2015

insert update delete using ajax asp.net

No comments
Reference Codingfusion.com




Database

Id           int   
Name    varchar(50)   
Email    varchar(50)   
Age       nchar(10)   


Than import jquery plugin or add javascript src in head.

for offline :- HERE
for online:-
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

Edit/Delete Image



.CSS

<style type="text/css">
  body
        {
            font-family: Verdana;
            font-size: 11px;
        }
       
       .errmsg,.errmsgpop
        {
            width: 200px;
            text-align: left;
            color: yellow;
            font: 12px arial;
            background: red;
            padding: 5px;
            display: none;
        }
       
        #tblResult
        {
            border-collapse: collapse;
        }
        #tblResult td
        {
            padding: 5px;
            border: 1px solid red;
        }
        #tblResult th
        {
            padding: 5px;
            border: 1px solid red;
        }
    </style>

BODY


<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table class="style1">
        <tr>
            <td colspan="3">
                <div class="errmsg">
                </div>              
            </td>
        </tr>
        <tr>
            <td class="style2">
                <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style2">
                <asp:Label ID="Label2" runat="server" Text="Email"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtmail" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style2">
                <asp:Label ID="Label3" runat="server" Text="Age"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtage" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style2">
            </td>
            <td>
                <input type="button" value="Submit" title="Submit" id="btnsubmit" onclick="saveData()" />             
                <asp:HiddenField ID="hiddn" runat="server" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <div id="allData">
                </div>
            </td>
        </tr>
    </table>


 <%--popup --%>

    <div id="pop" title="Update Data">
        <p>
            <table class="style1" style="display: none" id="tblpop">
                <tr>
                    <td colspan="3">
                        <div class="errmsgpop">
                        </div>
                        <br />
                        <br />
                    </td>
                </tr>
                <tr>
                    <td class="style2">
                        <asp:Label ID="Label4" runat="server" Text="Name"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="nametxt" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="style2">
                        <asp:Label ID="Label5" runat="server" Text="Email"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="mailtxt" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="style2">
                        <asp:Label ID="Label6" runat="server" Text="Age"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="agetxt" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="style2">
                        &nbsp;
                    </td>
                    <td>
                        <input type="button" value="Update" title="Update" id="btnupp" onclick="updateData()" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div id="Div1">
                        </div>
                    </td>
                </tr>
            </table>
        </p>
    </div>

</asp:Content>

Important NameSpace



using System.Web.Services;
using System.Web.Script.Serialization;

FOR INSERTING DATA(saveData)

.CS


[WebMethod]
    public static int saveData(string name, string email, string age)
    {
        string data = string.Empty;
        using (SqlConnection con = new SqlConnection("connectionstring"))
        {
            using (SqlCommand cmd = new SqlCommand("insert into Jquery_Test(Name,Email,Age) output INSERTED.Id values(@name,@email,@age)", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@name", name);
                cmd.Parameters.AddWithValue("@age", age);
                cmd.Parameters.AddWithValue("@email", email);
                int i = (int)cmd.ExecuteScalar();
                con.Close();
                return i;
            }
        }
    }


JQUERY



 function saveData() {
            var count = validateData();
            if (count == 0) {

                var name = $('#MainContent_txtname').val();
                var age = $('#MainContent_txtage').val();
                var email = $('#MainContent_txtmail').val();

                $.ajax({
                    type: "POST",
                    url: "Ajx_insrt_updt.aspx/saveData",
                    data: "{name:'" + name + "',age:'" + age + "',email:'" + email + "'}",
                    contentType: "application/json;context=utf-8",
                    datatype: "jsondata",
                    success: function (response) {
                        var msg = eval('(' + response.d + ')');
                        if (msg > 0) {
                            $('.errmsg ul').remove();
                            $('.errmsg').append("<ul><li>Data Inserted Sucessfully</li></ul>");
                            $('.errmsg').slideDown("slow");
                            clear();
                            bindData();
                        }
                        else {
                            $('.errmsg').append("<ul><li>Error Occured</li></ul>");
                        }
                    },
                    error: function (response) {
                        alert('Error');
                    }
                });
            }
        }

Binding Data To Table(bindData)

.CS


 [WebMethod]
    public static string bindData()
    {
        string data = string.Empty;
        using (SqlConnection con = new SqlConnection("connectionstring"))
        {
            using (SqlCommand cmd = new SqlCommand("select * from Jquery_Test", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                Dictionary<string, object> dict;
                foreach (DataRow dr in dt.Rows)
                {
                    dict = new Dictionary<string, object>();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        dict.Add(dc.ColumnName, dr[dc]);
                    }
                    list.Add(dict);
                }
                JavaScriptSerializer json = new JavaScriptSerializer();
                data = json.Serialize(list);
            }
        }
        return data;

JQUERY

  function bindData() {
            $.ajax({
                type: "POST",
                url: "Ajx_insrt_updt.aspx/bindData",
                data: "{}",
                contentType: "application/json;context=utf-8",
                datatype: "jsondata",
                async: "true",
                success: function (response) {
                    var msg = eval('(' + response.d + ')');
                    if ($('#tblResult').length != 0) {
                        $('#tblResult').remove();
                    }

                    var table = "<table id='tblResult' class='tblResult'><thead><tr><th>Name</th><th>Email</th><th>Age</th><th>Action</th></tr></thead><tbody>";
                    for (var i = 0; i <= (msg.length - 1); i++) {
                        var data = "<tr>"
                        data += '<td>' + msg[i].Name + '</td>';
                        data += '<td>' + msg[i].Email + '</td>';
                        data += '<td>' + msg[i].Age + '</td>';
                        data += '<td><img src="edit.png" title="Edit Data" onclick="editData(' + msg[i].Id + ')"/><img src="delete.png" title="Delete Data" onclick="deleteData(' + msg[i].Id + ')"/></td>';
                        data += '</tr>'
                        table += data;
                    }
                    table += '</tbody></table>';
                    $('#allData').html(table);
                    $('#allData').slideDown("slow");
                },
                error: function (response) {
                    alert('error');
                }
            });
        }

Editing Data(editData).CS

 [WebMethod]
    public static string editData(int id)
    {
        string data = string.Empty;
        using (SqlConnection con = new SqlConnection("connectionstring"))
        {
            using (SqlCommand cmd = new SqlCommand("select * from Jquery_Test where id=@id", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@id", id);
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                con.Close();
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                Dictionary<string, object> dict;
                foreach (DataRow dr in dt.Rows)
                {
                    dict = new Dictionary<string, object>();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        dict.Add(dc.ColumnName, dr[dc]);
                    }
                    list.Add(dict);
                }
                JavaScriptSerializer json = new JavaScriptSerializer();
                data = json.Serialize(list);
                string x = data.Remove(0, 1);
                data = x.Remove(x.Length - 1);
            }
        }
        return data;
    }


JQUERY

function editData(id) {

//For Opening Popup while edit data

  $(document).ready(function () {
                $("#pop").dialog({ autoOpen: false });
                $("#pop").dialog("open");
                $("#tblpop").css('display', 'block');
            });
            $.ajax({
                type: "POST",
                url: "Ajx_insrt_updt.aspx/editData",
                data: "{id:'" + id + "'}",
                contentType: "application/json;context=utf-8",
                datatype: "jsondata",
                async: "true",
                success: function (response) {
                    var msg = eval('(' + response.d + ')');

                    $('#MainContent_nametxt').val(msg.Name);
                    $('#MainContent_
agetxt').val(msg.Age);
                    $('#MainContent_mailtxt').val(msg.Email);                
                    $('#MainContent_hiddn').val(id);
                    $('#btnsubmit').hide();
                    $('#btnUpdate').css('display', 'block');
                },
                error: function (response) {
                    alert('error');
                }
            });
        }

Updating Data(updateData)

.CS

 [WebMethod]
    public static int updateData(string name, string email, string age, int id)
    {
        int status = 0;
        using (SqlConnection con = new SqlConnection("connectionstring"))
        {
            using (SqlCommand cmd = new SqlCommand("update Jquery_Test set name=@name,email=@email,age=@age where id=@id", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@name", name);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@age", age);
                cmd.Parameters.AddWithValue("@id", id);
                cmd.ExecuteNonQuery();
                con.Close();
                status = id;
            }
        }
        return status;
    }

JQUERY

  function updateData() {
            var validate = validatePopup();
            if (validate == 0) {

                var txtname = $('#MainContent_nametxt').val();
                var txtmaeil = $('#MainContent_mailtxt').val();
                var txtage = $('#MainContent_agetxt').val();             
                var id = $('#MainContent_hiddn').val();
                $.ajax({
                    type: "POST",
                    url: "Ajx_insrt_updt.aspx/updateData",
                    data: "{name:'" + txtname + "',email:'" + txtmaeil + "',age:'" + txtage + "',id:'" + id + "'}",
                    contentType: "application/json;context=utf-8",
                    datatype: "jsondata",
                    success: function (response) {
                        $('.errmsg ul').remove();
                        var msg = eval('(' + response.d + ')');
                        if (msg > 0) {
                            bindData();                           
                            $('.errmsg').append("<ul><li>Data Updated Sucessfully</li></ul>");
                            $('.errmsg').fadeTo(1000, 1).fadeOut(3000);
                            clear();
//hiding popup
                            $("#tblpop").css('display', 'none');
                            $("#hello").dialog({ autoOpen: false });
                            $("#hello").dialog("close");
                        }
                        else {
                            $('.errmsg').append("<ul><li>SOmething went wrong</li></ul>");
                        }
                    },
                    error: function (response) {
                        alert('error');
                    }
                });
            }
        }


Deleting Data(deleteData)

.CS

 [WebMethod]

    public static void deleteData(int id)
    {       
        using (SqlConnection con = new SqlConnection("connetionstring"))
        {
            using (SqlCommand cmd = new SqlCommand("delete from Jquery_Test where id=@id", con))
            {
                con.Open();               
                cmd.Parameters.AddWithValue("@id", id);
                cmd.ExecuteNonQuery();
                con.Close();       
            }
        }       
    }

JQUERY

 function deleteData(id) {
            if (confirm('are you sure wants to delete') == true) {

                $.ajax({
                    type: "POST",
                    url: "Ajx_insrt_updt.aspx/deleteData",
                    data: "{id:'" + id + "'}",
                    contentType: "application/json;context=utf-8",
                    datatype: "jsondata",
                    success: function (response) {
                        bindData();
                        $('.errmsg ul').remove();
                        $('.errmsg').append("<ul><li>data deleted successfully</li></ul>");
                        $('.errmsg').slideDown("slow");
                        clear();
                    },
                    error: function (response) {
                        alert('error in updating data');
                    }

                });
            }

            else {
                return false;
            }
        }

For clearing and binding data(at loading time)

JQUERY

 $(document).ready(function () {
            bindData();
        });//for clearing data
        function clear() {
            $('#MainContent_txtname').val("");
            $('#MainContent_txtage').val("");
            $('#MainContent_txtmail').val("");
          

            $('#MainContent_nametxt').val("");
            $('#MainContent_mailage').val("");
            $('#MainContent_mailtxt').val("");
            $('.errmsgpop ul').remove()      
//for validating data

 
  function validateData() {
            var name = $('#MainContent_txtname').val();
            var age = $('#MainContent_txtage').val();
            var email = $('#MainContent_txtmail').val();
            var count = 0
            var errmsg = '';
            if (name.length <= 0) {
                count++;
                errmsg += "<li>Please enter name</li>";
            }
            if (age.length <= 0) {
                count++;
                errmsg += "<li>Please enter age</li>";
            }
            if (email.length <= 0) {
                count++;
                errmsg += "<li>Please enter mail</li>";
            }
            if (count > 0) {
                $('.errmsg ul').remove();
                $('.errmsg').append("<ul>" + errmsg + "</ul>");
                $('.errmsg  ').slideDown("slow");
            }
            return count;
        }


        function validatePopup() {

            var name = $('#MainContent_nametxt').val();
            var age = $('#MainContent_agetxt').val();
            var email = $('#MainContent_mailtxt').val();
            var count = 0
            var errmsg = '';
            if (name.length <= 0) {
                count++;
                errmsg += "<li>Please enter name</li>";
            }
            if (age.length <= 0) {
                count++;
                errmsg += "<li>Please enter age</li>";
            }
            if (email.length <= 0) {
                count++;
                errmsg += "<li>Please enter mail</li>";
            }
            if (count > 0) {
                $('.errmsgpop ul').remove();
                $('.errmsgpop').append("<ul>" + errmsg + "</ul>");
                //$('.errmsgpop').fadeTo(1000, 1).fadeOut(8000);
                $('.errmsgpop').slideDown("slow");
            }
            return count;
        }
        }
read more