Skip to main content

CRUD Operation in ASP.NET MVC Using ADO.NET Jquery Ajax

In this article of ASP.NET MVC we will learn about CRUD operation using jquery ajax so let's start.



Firstly open visual studio:




Go to File => New and Select Project,when you select project then New Project Dialogbox will appear.
Select ASP.NET Web Application (.NET Framework) and give a name to your project , as we are building CRUD Operation so our project's name could be CRUD_OPEATION and then select OK.



Now you will see a new dialogbox, select Empty Template and MVC folder.




After create project you will see a like screen like this:



Now go to Models folder and add ADO.NET Entity Data Model and give any name like in my case i give dbEntities and selec OK:





After that you will see a dilogbox called Entity Data Model Wizard, select EF Designer from database and select Next:




After that a new dilogbox will appear and it will ask a new connection to your sql server,
then select New Connection and give server name ( if you want to see your server name then open sql server,it will appear a dialog box will a server name , copy that code and paste on your server visual studio's server name after that you will be ask to select database, select your database and Click Ok (Remember i have a database file so that's why i am able to select database but if you have dont have a database so firstly create a database.





After Click Ok you will see a screen,dont do anything just Click Next Button



Select a Entity Framework 5.0 and click Next




After that , it will ask you to select Database Tables , i have create my table namely called dboLogin
so i selected and CLICK Finish button.





When everything will be okay then you must see the screen below:













Now Lets start coding part.


Firstly add Folder called Repository in your Project Solution and inside folder add a class namely called EmpRepository and write a code below:






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

namespace Kassim.Repository
{
    public class EmpRepository
    {
        string strCon = "Data Source=NAVEED-PC;Initial Catalog=Naveed;Integrated Security=True";
        DataTable dt = new DataTable();

        public DataTable GetAllEmployee()
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from EmpLoyeeDetail", con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
            }
            return dt;
        }

        public DataTable GetEmployeeById(int id)
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();

                SqlCommand cmd = new SqlCommand();
                SqlDataAdapter da = new SqlDataAdapter("select * from EmpLoyeeDetail where id =" + id, con);
                da.Fill(dt);
            }
            return dt;

        }

        public int DeleteRecord(int strId)
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();
                string query = "delete from EmpLoyeeDetail where id =@id";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@id", strId);
                return cmd.ExecuteNonQuery();
            }
        }
        public int UpdateRecord(string strFatherName, string strAddress, string strPhoneNo,string strMobileNo,string strBloodGroup, int strId)
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                con.Open();

                string query = "update EmpLoyeeDetail set FatherName =@stFatherName, Address= @stAddress, PhoneNo=@stPhoneNo , MobileNo = @stMobileNo , BloodGroup = @stBloodGroup where id = @stId";

                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@stFatherName", strFatherName);
                cmd.Parameters.AddWithValue("@stAddress", strAddress);
                cmd.Parameters.AddWithValue("@stPhoneNo", strPhoneNo);
                cmd.Parameters.AddWithValue("@stMobileNo", strMobileNo);
                cmd.Parameters.AddWithValue("@stBloodGroup", strBloodGroup);
                cmd.Parameters.AddWithValue("@stId", strId);

                return cmd.ExecuteNonQuery();
            }

        }
    }
}
















Create a controller, in my case i have created a controller called HomeController but you can take any name ,its depend on you.




HomeController:



using Kassim.Models;
using Kassim.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Kassim.Controllers
{
   
    public class HomeController : Controller
    {
        dbEntities db = new dbEntities();
        string strCon = "Data Source=NAVEED-PC;Initial Catalog=Naveed;Integrated Security=True";

        public ActionResult Dashboard()
        {
            EmpRepository emp = new EmpRepository();
            DataTable dt = emp.GetAllEmployee();
            return View(dt);
        }
        public ActionResult Details(int id)
        {
            EmpLoyeeDetail emp = new EmpLoyeeDetail();
            //EmpRepository emp = new EmpRepository();

            var list = db.Database.SqlQuery<EmpLoyeeDetail>("select * from EmpLoyeeDetail where id = " + id).ToList();

           
            return Json(list , JsonRequestBehavior.AllowGet);
            //DataTable dt = emp.GetEmployeeById(id);

            ////if (dt.Rows.Count > 0)
            //{

            //    return Json("dd",JsonRequestBehavior.AllowGet);
            //}
            //else
            //{
            //    return Json("dd", JsonRequestBehavior.AllowGet);
            //}
        }




        public ActionResult Edit(int id)
        {

            EmpRepository emp = new EmpRepository();
            DataTable dt = emp.GetEmployeeById(id);
            if (dt.Rows.Count > 0)
            {
               

                return View(dt);
            }
            else
            {
               
                return View(dt);
            }
          
        }
        public ActionResult UpdateRecord(FormCollection frm, string action)
        {
            if (action == "Submit")
            {


                EmpRepository emp = new EmpRepository();
                string fathername = frm["txtFatherName"];
                string address = frm["txtAddress"];
                string phoneno = frm["txtPhoneNo"];
                string mobileno = frm["txtMobileNo"];
                string bloodgroup = frm["txtBloodGroup"];

                int hdId = Convert.ToInt32(frm["hdId"]);


                int status = emp.UpdateRecord(fathername,address,phoneno,mobileno,bloodgroup,hdId);


                return RedirectToAction("Dashboard");
            }
            else
            {
                return RedirectToAction("Dashboard");

            }
        }
        public ActionResult Delete(int id)
        {

            //var list = db.Database.SqlQuery<EmpLoyeeDetail>("delete from EmpLoyeeDetail where id = " + deleterecord);
            //return Json(list, JsonRequestBehavior.AllowGet);
            try
            {
                // TODO: Add delete logic here
                EmpRepository emp = new EmpRepository();
                emp.DeleteRecord(id);
                return RedirectToAction("Dashboard");
            }
            catch
            {
                return View("Dashboard");
            }
        }


    }
}











Create a view called Dashboard and write a code below:


@using System.Data
@using System.Data.SqlClient
@model System.Data.DataTable
    @{
        ViewBag.Title = "Dashboard";

    }

    <!DOCTYPE html>
    <html>

    <head>

        <link href="~/css/StyleSheet1.css" rel="stylesheet" />



        <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">

    </head>

    <body>


       
        <!-- Modal -->
        <div class="modal fade " id="myModal" role="dialog">
            <div class="modal-dialog">

                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title text-center">Employee Details</h4>
                    </div>
                    <div class="modal-body">
                  

                        <input type="hidden" id="txtId" name="txtId" value="" />
                       

                        <table class="table table-bordered table-condensed table-responsive table-hover font-family-changer " id="empTable" border="1" data-toggle="modal" data-target="#myModal" >
                            <thead>
                                <tr class="table-background-color-changer table-thead-text-size-changer text-color-changer text-center" >

                                    <td>Father Name</td>
                                    <td>Address</td>
                                    <td>Phone No</td>
                                    <td>Mobile No</td>
                                    <td>Blood Group</td>
                                </tr>
                            </thead>

                            <tbody>
                                <tr class="text-center" >


                                    <td id="fathername"></td>
                                    <td id="address"></td>
                                    <td id="phoneno"></td>
                                    <td id="mobileno"> </td>
                                    <td id="bloodgroup"></td>



                                    @*<td>@fathername</td>
                                        <td>@address</td>
                                        <td>@phoneno</td>
                                        <td>@mobileno</td>
                                        <td>@bloodgroup</td>*@


                                </tr>
                            </tbody>
                        </table>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>

            </div>
        </div>

          



        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 font-family-changer">



            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 column_size_changer " id="homeDashboard">


                <p class=" text-right  text-size-changer  ">Home / Dashboard</p>

            </div>


            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 column_size_changer success_">

                <p class="text-size-changer messageBoxLabel "></p>


            </div>




            <form method="post" name="Display" class="tableTable">

                <br />


                @{

                    if (Model.Rows.Count > 0)
                    {
                        <table class="table table-bordered table-condensed table-responsive table-hover " id="myTable" border="1">
                            <thead>
                                <tr class="table-background-color-changer table-thead-text-size-changer text-color-changer text-center">

                                    <td>Employee Id</td>
                                    <td>Father Name</td>
                                    <td>Action</td>
                                </tr>
                            </thead>



                            <tbody>
                                @foreach (DataRow dr in Model.Rows)
                                {

                                    <tr class="text-center">
                                        <td>@dr["id"].ToString()</td>
                                        <td>@dr["FatherName"].ToString()</td>

                                        <td>

                                            @*<button type="button" value="@dr["id"].ToString()" data-toggle="modal" data-target="#myModal" class="btn btn-default " id="BtnDetail">Detail</button>*@
                                            @Html.ActionLink("Edit", "Edit", new { id = dr["id"].ToString() }, new { @class = "fa fa-pencil-square-o", @style = "text-decoration:none;" })


                                            @Html.ActionLink("Details", "", new { id = dr["id"].ToString() }, new { data_toggle = "modal", data_target = "#myModal", @class = "fa fa-info-circle   BtnDetails", @style= "margin-left:6px; text-decoration:none;" })
                                            @Html.ActionLink("Delete", "Delete", new { id = dr["id"].ToString() }, new { @class = "fa fa-trash  deleteBtn", @style = "margin-left:6px; text-decoration:none;" })

                                        </td>
                                    </tr>  


                                }
                            </tbody>
                        </table>
                        <br />
                    }
                    else
                    {
                        <span><b>No records found!!</b> </span>
                    }
                }

            </form>
        </div>




        <script>



            $(document).ready(function () {
              
                $(".deleteBtn").click(function () {
                    $("#messageBoxLabel").fadeIn().delay(10000).fadeOut();
                });
                var oTable = $('#myTable').dataTable();

                $("#myTable tbody").on('click', 'tr', function () {

                  

                    var id = $(this).find("td:eq(0)").text();
                   

                    var data = $('.modal-body #txtId').val(id);

                  
                   
                    $.ajax({
                        url: "/Home/Details",
                        type: "GET",
                        dataType: "JSON",
                        data: { id: id },

                        success: function (result) {
                            //alert(JSON.stringify(result));
                            $("#empTable tbody #fathername").text(result[0].FatherName);
                            $("#empTable tbody #address").text(result[0].Address);
                            $("#empTable tbody #phoneno").text(result[0].PhoneNo);
                            $("#empTable tbody #mobileno").text(result[0].MobileNo);
                            $("#empTable tbody #bloodgroup").text(result[0].BloodGroup);
                       

                        },
                        error: function (err) {
                            //alert("error");
                        },


                    });



                });


  


              

        </script>


    </body>
</html>















Add another view called Details and write a code below:



@using System.Data
@using System.Data.SqlClient
@model System.Data.DataTable
@{
  
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Details</title>
</head>
<body>
  
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 column_size_changer font-family-changer" >


        <p class="text-right  text-size-changer" >Home / Detail</p>

    </div>



    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 column_size_changer">
        @{
            var message = "";
            var fathername = "";
            var address = "";
            var phoneno = "";
            var mobileno = "";
            var bloodgroup = "";
            //var id = "";
        }

        @if (Model.Rows.Count == 0)
        {
            message = "Invalid Information";
            fathername = "";
            address = "";
            phoneno = "";
            mobileno = "";
            bloodgroup = "";
            //id = "";
        }
        else
        {
            message = "";
            fathername = Model.Rows[0]["FatherName"].ToString();
            address = Model.Rows[0]["Address"].ToString();
            phoneno = Model.Rows[0]["PhoneNo"].ToString();
            mobileno = Model.Rows[0]["MobileNo"].ToString();
            bloodgroup = Model.Rows[0]["BloodGroup"].ToString();
            //id = Model.Rows[0]["id"].ToString();

        }
        <p class="text-size-changer font-family-changer" style="">@message</p>



       

    </div>

    <table class="table table-bordered table-condensed table-responsive table-hover font-family-changer" border="1">
        <thead>
            <tr>

                <td>Father Name</td>
                <td>Address</td>
                <td>Phone No</td>
                <td>Mobile No</td>
                <td>Blood Group</td>
            </tr>
        </thead>

        <tbody>
            <tr>

                <td>@fathername</td>
                <td>@address</td>
                <td>@phoneno</td>
                <td>@mobileno</td>
                <td>@bloodgroup</td>


            </tr>
        </tbody>
    </table>
</body>
</html>















Add view called Edit :

@using System.Data
@using System.Data.SqlClient
@model System.Data.DataTable
@{



}

<!DOCTYPE html>

<html>
<head>


    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>

    <link href="~/css/StyleSheet1.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/sweetalert2/6.4.3/sweetalert2.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/sweetalert2/latest/sweetalert2.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

</head>
<body>

   
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 column_size_changer">


        <p class="text-right  text-size-changer" style="color:black;">Home / Edit</p>

    </div>




    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 column_size_changer">
        @{
            var message = "";
            var fathername ="";
            var address = "";
            var phoneno = "";
            var mobileno = "";
            var bloodgroup = "";
            var id = "";
        }

        @if (Model.Rows.Count == 0)
        {
           
            message = "No Record Found !!!";
            fathername = "";
            address = "";
            phoneno = "";
            mobileno = "";
            bloodgroup = "";
            id = "";

            <script>
                $(document).ready(function () {

                    $(".txtFatherName").prop("readonly", true);
                    $(".txtAddress").prop("readonly", true);
                    $(".txtPhoneNo").prop("readonly", true);
                    $(".txtMobileNo").prop("readonly", true);
                    $(".txtBloodGroup").prop("readonly", true);
                    $(".btnSubmit").prop("disabled", true);
                   
                });
            </script>
        }
        else
        {
            message = "";
            fathername=Model.Rows[0]["FatherName"].ToString();
            address = Model.Rows[0]["Address"].ToString();
            phoneno = Model.Rows[0]["PhoneNo"].ToString();
            mobileno = Model.Rows[0]["MobileNo"].ToString();
            bloodgroup = Model.Rows[0]["BloodGroup"].ToString();
            id = Model.Rows[0]["id"].ToString();

        }
        <p class="text-size-changer font-family-changer" style="">@message</p>
    </div>

    <div class="container">
        <div id="loginbox" style="" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-xs-12 col-sm-offset-2 font-family-changer">
            <div class="panel panel-info">
                <div class="panel-heading text-size-changer table-background-color-changer">
                    <div class="panel-title table-thead-text-size-changer text-center text-color-changer ">Update Record</div>

                </div>
                <div style="" class="panel-body">
                    <div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>

                    <form id="loginform" class="form-horizontal" role="form" method="post" action="@Url.Action("UpdateRecord")">


                        <div class="">
                            <span>Father Name</span>
                        </div>
                        <div style="margin-bottom: 25px" class="input-group">


                            <span class="input-group-addon table-background-color-changer text-color-changer "><i class="glyphicon glyphicon-user"></i></span>
                            <input type="text" name="txtFatherName" value="@fathername" class="form-control txtFatherName" required/>
                        </div>


                        <div class="">
                            <span>Enter Address</span>
                        </div>
                        <div style="margin-bottom: 25px" class="input-group">
                            <span class="input-group-addon table-background-color-changer text-color-changer"><i class="glyphicon glyphicon-lock"></i></span>
                            <input type="text" name="txtAddress"  value="@address" class="form-control txtAddress" required/>

                        </div>





                        <div class="">
                            <span>Enter Phone No</span>
                        </div>
                        <div style="margin-bottom: 25px" class="input-group">
                            <span class="input-group-addon table-background-color-changer text-color-changer"><i class="glyphicon glyphicon-lock"></i></span>

                            <input type="text" name="txtPhoneNo" value="@phoneno" class="form-control txtPhoneNo" required/>
                        </div>



                        <div class="">
                            <span>Enter Mobile No</span>
                        </div>
                        <div style="margin-bottom: 25px" class="input-group">
                            <span class="input-group-addon table-background-color-changer text-color-changer"><i class="glyphicon glyphicon-lock"></i></span>

                            <input type="text" name="txtMobileNo" value="@mobileno" class="form-control txtMobileNo" required/>
                        </div>



                        <div class="">
                            <span>Enter Blood Group</span>
                        </div>
                        <div style="margin-bottom: 25px" class="input-group">
                            <span class="input-group-addon table-background-color-changer text-color-changer"><i class="glyphicon glyphicon-lock"></i></span>


                            <input type="text" name="txtBloodGroup" value="@bloodgroup" class="form-control txtBloodGroup" required/>
                        </div>




                        <div style="margin-top:10px" class="form-group">
                            <!-- Button -->
                            <div class="col-sm-12 controls">

                                <input type="hidden" name="hdId" value="@id" />
                                <input type="submit" value="Submit" name="action" class="btn  table-background-color-changer text-color-changer btnSubmit " />
                                <input type="submit" value="Cancel" name="action" class="btn table-background-color-changer text-color-changer" />
                            </div>
                        </div>



                    </form>

                </div>
            </div>
        </div>

    </div>


    </script>
</body>
</html>



Thank you.


Comments

Popular posts from this blog

SignIn_SignUp in Asp.net Mvc

Models: SignUp Class: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace Signin_Signup.Models {     [Table("tbl_account")]     public class SignUp     {         public int id { get; set; }         public string name { get; set; }         public string email { get; set; }         public string password { get; set; }     } } DB Class: using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace Signin_Signup.Models {     public class db:DbContext     {         public DbSet<SignUp> signups { get; set; }     } } User Controller: using Signin_Signup.Models; using System; using System.Collections.Generic; using System.L...

ASP.NET MVC Folder and File Structure

When we create an ASP.NET MVC 5 application, the Visual Studio by default creates the following folders and files for our application. App_Data App_Data folder can contain application data files like LocalDB, .mdf files, xml files and other data related files. App_Start: The App_Start folder of an MVC application is used to contain the class files which are needed to be executed at the time of application starts. The classes like BundleConfig, FilterConfig, RouteConfig, IdentityConfig, etc are stored within this folder. So in the simple word we can say that configuration related class files are stored here.  We will discuss the use of each of these class files in detail in our upcoming articles. Content Content folder contain static files like css, images and icons and MVC 5 application includes bootstrap.min.css, bootstrap.css and site.css by default. Controller Controller folder contain class file. It handles user request and response....