Saturday 21 November 2015

CRUD operation in asp.net without any postback using html control


CRUD operation on client side






Description:-

In this example we explain that how to perform insert, update, delete operation in asp.net without any post back using HTML control.

Previously we already explain that how to perform CRUD operation in asp.net without post back on client side code. Here the concept is same but we only use HTML control not any asp.net control.


Here we use jQuery ajax web method for perform all insert, update and delete operation.so how to display data to html table control look like grid view In asp.net and perform all the operation on client side without page load or post back using jQuery ajax web method.



StudentEntry.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentEntry.aspx.cs" Inherits="KiritDemo.StudentEntry" %>


<!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">

    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        //Function For Clear all control after Insert and Update Operation

        function ClearControl() {

            $("[id*=txtName]").val("");

            $('#rdbmale').attr('checked', 'checked');


        }

        //Function For Rebind Student Data

        function BindStudent(Operation) {

          

            $(document).ready(function () {


                             var student = {};

                            student.SRNO = "0";

                $.ajax({

                    type: "POST",

                    contentType: "application/json; charset=utf-8",

                    url: "StudentEntry.aspx/BindStudent",

                   // data: '{}',

                                       data: '{student: ' + JSON.stringify(student) + '}',

                    dataType: "json",

                    success: function (data) {


                        if (data.d != null) {

                            $("#studentDetails tbody tr").each(function () {

                                this.parentNode.removeChild(this);

                            });

                            for (var i = 0; i < data.d.length; i++) {

                                $("#studentDetails").append("<tr><td class='srno'>" + data.d[i].SRNO + "</td><td class='name'>" + data.d[i].Name + "</td><td class='gender'>" + data.d[i].Gender + "</td><td><a Style='color: blue;cursor:pointer' class='remove' id='" + data.d[i].SRNO + "'>Delete</a></td><td><a Style='color: blue;cursor:pointer' class='edit' id='" + data.d[i].SRNO + "'>Edit</a></td></tr>");

                            }

                            if (Operation == "Insert")

                                $("[id*=txtSrNo]").val((data.d[i - 1].SRNO) + 1);

                        }

                        else

                            alert("Some error may have occured while executing your request, Please try later.");

                    },

                    error: function (xhr) {

                        var r = jQuery.parseJSON(xhr.responseText);

                        alert("Error Occured " + r.Message);

                    }

                });

            });

        }


        //Event For Delete Rows Based on SRNO

        $('.remove').live('click', function () {

            if (confirm('Are you sure you want to delete this record ?')) {

                var Id = ($(this).parent().parent().remove()).find(".remove").attr("id");

                var student = {};

                student.SRNO = Id;

                $.ajax({

                    type: "POST",

                    url: "StudentEntry.aspx/DeleteStudent",

                    data: '{student: ' + JSON.stringify(student) + '}',

                    contentType: "application/json; charset=utf-8",

                    dataType: "json",

                    success: function (response) {

                        if (response && response.d && response.d == "Success") {

                            alert("student has been Deleted successfully.");

                        }

                        else {

                            alert("Some error may have occured while executing your request, Please try later.");

                        }

                    },

                    error: function (xhr) {

                        var r = jQuery.parseJSON(xhr.responseText);

                        alert("Error Occured " + r.Message);

                    }


                });

                console.log($(this).parent().parent().remove())

            }

        });



        //Event for set the Edit Value to Control Before Update

        $('.edit').live('click', function () {

            var Id = ($(this).parent().parent().remove()).find(".edit").attr("id");

            var student = {};

            student.SRNO = Id;

            $.ajax({

                type: "POST",

                contentType: "application/json; charset=utf-8",

                url: "StudentEntry.aspx/BindStudent",

                data: '{student: ' + JSON.stringify(student) + '}',

                dataType: "json",

                success: function (data) {


                    if (data.d != null) {

                       

                        for (var i = 0; i < data.d.length; i++) {

                            $("[id*=txtSrNo]").val(data.d[i].SRNO);

                           // $("[id*=hdnSrNo]").val(Base64.encode(data.d[i].SRNO));

                            $("[id*=txtName]").val(data.d[i].Name);

                            if (data.d[i].Gender == "Male")

                                $('#rdbmale').attr('checked', 'checked');

                            else

                                $('#rdbfemale').attr('checked', 'checked');


                            $("[id*=btnAdd]").val("Update");

                            BindStudent("Edit");


                        }

                    }

                },

                error: function (xhr) {

                    var r = jQuery.parseJSON(xhr.responseText);

                    alert("Error Occured " + r.Message);

                }

            });




            //            var Id = ($(this).parent().parent().remove()).find(".edit").attr("id");

            //            var Name = ($(this).parent().parent().remove()).find(".name").html();

            //            var Gender = ($(this).parent().parent().remove()).find(".gender").html();


        });


        //Event for Insert and Update Operation in Student Table

        var isSubmitting = false;

        $(function (e) {


            $("[id*=btnAdd]").bind("click", function (e) {

                //e.preventDefault();


                var student = {};

                student.Name = $("[id*=txtName]").val();

                if (student.Name == "") {

                    alert("Enter Name");

                    return false;

                }

                student.Gender = $('input:radio[name=gender]:checked').val();

                if ($("[id*=btnAdd]").val() == "Add")

                    student.Operation = "Insert";

                else {

                    student.Operation = "Update";

                  

                    student.SRNO = $("[id*=txtSrNo]").val();

                }

                // e.stopImmediatePropagation();


                $.ajax({

                    type: "POST",

                    url: "StudentEntry.aspx/AddStudent",

                    data: '{student: ' + JSON.stringify(student) + '}',

                    contentType: "application/json; charset=utf-8",

                    dataType: "json",

                    success: function (response) {

                        if (response && response.d && response.d == "Success") {

                            if (student.Operation == "Insert")

                                alert("student has been added successfully.");

                            else if (student.Operation == "Update")

                                alert("student has been Updated successfully.");

                            BindStudent("Insert");

                            ClearControl();

                        }

                        else {

                            alert("Some error may have occured while executing your request, Please try later.");

                            // isSubmitting = false;


                        }

                    },

                    error: function (xhr) {

                        var r = jQuery.parseJSON(xhr.responseText);

                        alert("Error Occured " + r.Message);

                        // isSubmitting = false;

                    }


                });

                //                $("[id*=btnAdd]").unbind().click(function () {

                //                    //Stuff

                //                });

                return false;

            });

        });

    </script>

    <title></title>

</head>

<body onload="BindStudent('Insert')">

    <form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

    </asp:ScriptManager>

    <hr />

    <div id="divStatus" style="color: Red">

    </div>

    <label id="lblmsg" runat="server">

    </label>

    <table border="1" width="17%">

        <tr>

            <td>

                SR.NO:

            </td>

            <td>

                <input type="text" id="txtSrNo" runat="server" disabled="disabled" />

                <input type="hidden" id="hdnSrNo" />

            </td>

        </tr>

        <tr>

            <td>

                Name:

            </td>

            <td>

                <input type="text" id="txtName" />

            </td>

        </tr>

        <tr>

            <td>

                Gender:

            </td>

            <td>

                <input type="radio" name="gender" checked="checked" id="rdbmale" value="Male" />Male

                <input type="radio" name="gender" id="rdbfemale" value="Female" />Female

            </td>

        </tr>

        <tr>

            <td>

                <input type="button" id="btnAdd" value="Add" />

            </td>

            <td>

                <input type="button" id="btnCancel" value="Cancel" onclick="ClearControl()" />

            </td>

        </tr>

    </table>

    <table id="studentDetails" cellpadding="0" cellspacing="0" width="20%">

        <thead style="background-color: #DC5807; color: White; font-weight: bold">

            <tr style="border: solid 1px #000000">

                <td>

                    SRNO

                </td>

                <td>

                    Name

                </td>

                <td>

                    Gender

                </td>

                <td>

                    Delete

                </td>

                <td>

                    Edit

                </td>

            </tr>

    </form>

</body>

</html>

StudentEntry.aspx.cs:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Services;

using System.Web.Script.Services;

using System.Configuration;

using System.Data.SqlClient;

using System.Data;

using System.IO;


namespace KiritDemo

{


    public partial class StudentEntry : System.Web.UI.Page

    {


        protected void Page_Load(object sender, EventArgs e)

        {


        }

        /// <summary>

        ///  Insert or Update Student Details in Student table.

        /// </summary>

        /// <param name="Name"></param>

        ///  /// <param name="Gender"></param>

        /// <returns></returns>

        [WebMethod]

        [ScriptMethod]

        public static string AddStudent(Student student)

        {

            //var base64EncodedBytes = System.Convert.FromBase64String(Convert.ToString(student.SRNO));

            //student.Name = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

            string ResponseMessage = "";

            string constr = ConfigurationManager.ConnectionStrings["kiritdemoconnectionstring"].ConnectionString;

            SqlConnection con = null;

            SqlCommand cmd = null;

            try

            {

                con = new SqlConnection(constr);

                if (student.Operation == "Insert")

                    cmd = new SqlCommand("INSERT INTO Student VALUES(@Name, @Gender)");

                else

                    cmd = new SqlCommand("Update Student set Name = @Name,Gender = @Gender where SRNO = @SRNO");

                cmd.CommandType = CommandType.Text;

                cmd.Parameters.AddWithValue("@Name", student.Name);

                cmd.Parameters.AddWithValue("@Gender", student.Gender);

                cmd.Parameters.AddWithValue("@SRNO", student.SRNO);

                cmd.Connection = con;

                con.Open();

                cmd.ExecuteNonQuery();

                ResponseMessage = "Success";


            }

            catch (Exception ex)

            {

                ResponseMessage = "Error";

            }

            finally

            {

                con.Close();

            }

            return ResponseMessage;


        }


        /// <summary>

        ///  Delete Student Details in Student table based on Id.

        /// </summary>

        /// <param name="Id"></param>

        /// <returns></returns>

        [WebMethod]

        [ScriptMethod]

        public static string DeleteStudent(Student student)

        {

            string ResponseMessage = "";

            string constr = ConfigurationManager.ConnectionStrings["kiritdemoconnectionstring"].ConnectionString;

            SqlConnection con = null;

            try

            {

                con = new SqlConnection(constr);

                SqlCommand cmd = new SqlCommand("Delete From Student where SRNO = @SRNO");

                cmd.CommandType = CommandType.Text;

                cmd.Parameters.AddWithValue("@SRNO", student.SRNO);

                cmd.Connection = con;

                con.Open();

                cmd.ExecuteNonQuery();

                ResponseMessage = "Success";


            }

            catch (Exception ex)

            {

                ResponseMessage = "Error";

            }

            finally

            {

                con.Close();

            }

            return ResponseMessage;


        }


        /// <summary>

        ///  Bind Student Details in Table.

        /// </summary>

        [WebMethod]

        public static Student[] BindStudent(Student student)

        {

            string constr = ConfigurationManager.ConnectionStrings["kiritdemoconnectionstring"].ConnectionString;

            List<Student> details = new List<Student>();

            SqlConnection con = null;

            SqlCommand cmd =null;

            try

            {

                DataTable dt = new DataTable();

                con = new SqlConnection(constr);

                if(student.SRNO == 0)

                 cmd= new SqlCommand("select * from Student", con);

                else

                    cmd = new SqlCommand("select * from Student where SRNO ='"+student.SRNO+"'", con);

                con.Open();

                SqlDataAdapter da = new SqlDataAdapter(cmd);

                da.Fill(dt);

                foreach (DataRow dtrow in dt.Rows)

                {

                    Student students = new Student();

                    students.Name = dtrow["Name"].ToString();

                    students.Gender = dtrow["Gender"].ToString();

                    students.SRNO = Convert.ToInt32(dtrow["SRNO"]);

                    details.Add(students);

                }


                return details.ToArray();

            }

            catch (Exception ex)

            {

                return null;


            }

            finally

            {

                con.Close();

            }



        }

        public class Student

        {

            public int SRNO { get; set; }

            public string Name { get; set; }

            public string Gender { get; set; }

            public string Operation { get; set; }

        }

    }

}

1 comments:

  1. Its my favorite programming language and i want to learn it more and learn advanced.
    Good Night Images for lover

    ReplyDelete