Saturday, 25 July 2015

Insert Update Delete in ASP.NET using Jquery (Ajax/Json)

Create table UserList
Use following query to create table:

CREATE TABLE [dbo].[UserList](
       [UserName] [varchar](100) NULL,
       [Password] [varchar](100) NULL
)




Arrange your file in solutions explorer in given below manner.


Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script src="Scripts/Default.js" type="text/javascript"></script>
</head>
<body style="margin:10px">
    <form id="form1" runat="server" autocomplete="off">
    <div>
        <table border="0" class="table-condensed" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            Username:
        </td>
        <td>
            <asp:TextBox ID="txtUsername" runat="server" Text="" />
        </td>
    </tr>
    <tr>
        <td>
            Password:
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button ID="btnSave" CssClass="btn btn-success" Text="Save" runat="server" />
            <asp:Button ID="btnMessage" CssClass="btn btn-info" Text="Load Data" runat="server" />
            <%--<input  type="button" value="click me" onclick="asyncServerCall(1);" />--%>
        </td>
    </tr>
</table>
<hr />
<asp:GridView ID="gvUsers" runat="server" CssClass="table-condensed" HeaderStyle-BackColor="#3AC0F2"
    HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2">
</asp:GridView>
    </div>
    <div>
        <table id="gvUsersTable" style="margin-left:10px;font-family:Courier New" class="table-condensed table-bordered">
           
        </table>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

* Add below namespaces

using System.Web.Services;
using System.Web.Script.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;



 [WebMethod]
        [ScriptMethod]
        public static List<User> getUserData()
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            List<User> details = new List<User>();
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM UserList"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                       
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        sda.Fill(dt);
                        foreach (DataRow dtrow in dt.Rows)
                        {
                            User user = new User();
                            user.Username = dtrow["UserName"].ToString();
                            user.Password = dtrow["Password"].ToString();
                            details.Add(user);
                        }
                    }
                }
            }
            return details;
        }

         
        [WebMethod]
        [ScriptMethod]
        public static void SaveUser(User user)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO UserList VALUES(@Username, @Password)"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Username", user.Username);
                    cmd.Parameters.AddWithValue("@Password", user.Password);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        [WebMethod]
        [ScriptMethod]
        public static void deleteUser(string id)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("delete UserList where UserName=@userName"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@userName", id);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

User.cs

public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

Default.js

/*submit*/

//Save into Database
$(function () {
    $("[id*=btnSave]").bind("click", function () {
        var user = {};
        $(this).attr('disabled', 'disabled');
        $(this).val('Please Wait...');
        user.Username = $("[id*=txtUsername]").val();
        user.Password = $("[id*=txtPassword]").val();
        if (user.Username != "" && user.Password != "") {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveUser",
                data: '{user: ' + JSON.stringify(user) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("User has been added successfully.");
                    $("#gvUsersTable").empty();
                    getUserList();
                    resetForm();
                }
            });
        }
        else {
            alert("Please fill the details !");
            $(this).removeAttr('disabled');
            $(this).val('Save');
        }
        return false;
    });
});

//Reset Form
function resetForm() {
    //After Save
    $("[id*=btnSave]").removeAttr('disabled');
    $("[id*=btnSave]").val("Save");
    $("[id*=txtUsername]").val("");
    $("[id*=txtPassword]").val("");

    //After Load
    $("[id*=btnMessage]").removeAttr('disabled');
    $("[id*=btnMessage]").val("Load Data");
}

//Get grid by Button
$(function () {
    $("[id*=btnMessage]").bind("click", function () {
        $(this).val("Please Wait...");
        $("#gvUsersTable").empty();
        getUserList();

        $(this).attr('disabled', 'disabled');

        return false;
    });
});

//Load grid after window Load
$(document).ready(function () {
    $(window).load(function () {
        getUserList();
    });
});

//Get UserList and bind it into table
function getUserList() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/getUserData",
        data: "{}",
        dataType: "json",
        success: function (data) {
            if (data.d.length > 0) {
                $("#gvUsersTable").append("<tr style='background-color:#3AC0F2'><th>UserName</th> <th>Password</th><th>Delete</th></tr>");
                for (var i = 0; i < data.d.length; i++) {
                    $("#gvUsersTable").append("<tr><td>" + data.d[i].Username + "</td><td>" + data.d[i].Password + "</td><td align='center'>" + "<button style='background-color:#F99292;border:0px none;border-radius:50px' onclick='javascript:deleteUser(this.value);return false;' value='" + data.d[i].Username + "'>&times;</button>" + "</td></tr>");
                }
            }
            resetForm();
        },
        error: function (result) {
            //alert("Error"+result);
        }
    });
}

//delete User from List
function deleteUser(id) {
    if (id == null || id == "") {
        alert("Id not Proper");
    }
    else {
        $.ajax({
            type: "POST",
            url: "Default.aspx/deleteUser",
            data: '{id: ' + JSON.stringify(id) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
               
                $("#gvUsersTable").empty();
                getUserList();
                alert("User has been deleted successfully.");
            }
        });
    }
    return false;
 }

Result



No comments:

Post a Comment