Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Sunday, August 27, 2017

Part 46 ADD Edit Record using Jquery DataTable



In this video you will be able to perform Adding and Editing records using Jquery dataTable.  This blog is the combination of  Part 20 and Part 45. So Please understand them completely and then only watch this. 

If you are new to DataTables then please download latest version of Jquery DataTable. Click here to download the latest version of Jquery Datatable and watch my previous tutorial to get step by step DataTable plugin installation guide. you can visit here: Integrate JQuery DataTable plugin into Asp.net MVC 

The expected output will be as what displayed in following image. 


# View Page (Index.cshtml)

Right click on your controller' s Index method and add a view. After adding view, replace content with below code. 

@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">

    <div class="col-md-3">

        @{ Html.RenderAction("SideMenu", "Test");}

    </div>

    <div class="col-md-9">

        <div class="well">
            <a href="#" class="btn btn-primary" onclick="AddEditEmployee(0)">New</a>
        </div>
        <table class="display" id="MyDataTable">
            <thead>
                <tr>
                    <th>
                        EmaployeeName
                    </th>
                    <th>
                        Department
                    </th>
                    <th>
                        Address
                    </th>
                    <th>
                        EmployeeId
                    </th>
                </tr>
            </thead>

            <tbody></tbody>

        </table>
        <div class="modal fade" id="myModal1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <a href="#" class="close" data-dismiss="modal">&times;</a>
                        <h3 class="modal-title">AddEdit Employee</h3>
                    </div>
                    <div class="modal-body" id="myModalBodyDiv1">


                    </div>


                </div>

            </div>

        </div>

        <input type="hidden" id="hiddenEmployeeId" />
    </div>
</div>

<script>

        $(document).ready(function () {

            // $("#MyDataTable").DataTable();

            GetEmployeeRecord();
        })
        var GetEmployeeRecord = function () {

            $.ajax({

                type: "Get",
                url: "/Test/GetEmployeeRecord",
                success: function (response) {

                    BindDataTable(response);

                }
            })

        }

        var BindDataTable = function (response) {

            $("#MyDataTable").DataTable({

                "aaData": response,
                "aoColumns": [

                    { "mData": "Name" },
                    { "mData": "DepartmentName" },
                    { "mData": "Address" },
                    {
                        "mData": "EmployeeId",
                        "render": function (EmployeeId, type, full, meta) {
                            debugger
                            return '<a href="#" onclick="AddEditEmployee(' + EmployeeId + ')"><i class="glyphicon glyphicon-pencil"></i></a>'
                        }
                    },


                ]

            });
        }

        var AddEditEmployee = function (employeeId) {

            var url = "/Test/AddEditEmployee?EmployeeId=" + employeeId;

            $("#myModalBodyDiv1").load(url, function () {
                $("#myModal1").modal("show");

            })

        }
</script>

  # ViewModel (EmployeeViewModel).

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }

        public string Name { get; set; }

        public Nullable<int> DepartmentId { get; set; }

        public string Address { get; set; }

        public Nullable<bool> IsDeleted { get; set; }

        //Custom attribute
        public string DepartmentName { get; set; }
        public bool Remember { get; set; }
        public string SiteName { get; set; }
       
    }
}

# Controller Code (TestController.cs)
Visit  Part 20  and understand how to perform add edit operation. Meanwhile you can copy below code to your Test controller. Watch above video for complete understanding.

 using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{

    public class TestController : Controller
    {

        public ActionResult Index()
        {
            MVCTutorialEntities db = new MVCTutorialEntities();

            List<Department> list = db.Departments.ToList();
            ViewBag.DepartmentList = new SelectList(list, "DepartmentId", "DepartmentName");

            List<EmployeeViewModel> listEmp = db.Employees.Where(x => x.IsDeleted == false).Select(x => new EmployeeViewModel { Name = x.Name, DepartmentName = x.Department.DepartmentName, Address = x.Address, EmployeeId = x.EmployeeId }).ToList();

            ViewBag.EmployeeList = listEmp;

            return View();
        }

        public ActionResult SideMenu()
        {
            return PartialView("SideMenu");
        }

 public JsonResult GetEmployeeRecord()
        {

            MVCTutorialEntities db = new MVCTutorialEntities();

            List<EmployeeViewModel> List = db.Employees.Select(x => new EmployeeViewModel
            {
                Name = x.Name,
                EmployeeId = x.EmployeeId,
                DepartmentId = x.DepartmentId,
                DepartmentName = x.Department.DepartmentName,
                Address = x.Address,
                IsDeleted = x.IsDeleted
            }).ToList();

            return Json(List, JsonRequestBehavior.AllowGet);

        }
        [HttpPost]
        public ActionResult Index(EmployeeViewModel model)
        {
            try
            {
                MVCTutorialEntities db = new MVCTutorialEntities();
                List<Department> list = db.Departments.ToList();
                ViewBag.DepartmentList = new SelectList(list, "DepartmentId", "DepartmentName");

                if (model.EmployeeId > 0)
                {
                    //update
                    Employee emp = db.Employees.SingleOrDefault(x => x.EmployeeId == model.EmployeeId && x.IsDeleted == false);

                    emp.DepartmentId = model.DepartmentId;
                    emp.Name = model.Name;
                    emp.Address = model.Address;
                    db.SaveChanges();


                }
                else
                {
                    //Insert
                    Employee emp = new Employee();
                    emp.Address = model.Address;
                    emp.Name = model.Name;
                    emp.DepartmentId = model.DepartmentId;
                    emp.IsDeleted = false;
                    db.Employees.Add(emp);
                    db.SaveChanges();

                }
                return View(model);

            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        public ActionResult AddEditEmployee(int EmployeeId)
        {
            MVCTutorialEntities db = new MVCTutorialEntities();
            List<Department> list = db.Departments.ToList();
            ViewBag.DepartmentList = new SelectList(list, "DepartmentId", "DepartmentName");

            EmployeeViewModel model = new EmployeeViewModel();

            if (EmployeeId > 0)
            {

                Employee emp = db.Employees.SingleOrDefault(x => x.EmployeeId == EmployeeId && x.IsDeleted == false);
                model.EmployeeId = emp.EmployeeId;
                model.DepartmentId = emp.DepartmentId;
                model.Name = emp.Name;
                model.Address = emp.Address;

            }
            return PartialView("Partial2", model);
        }


    }
}



All Code Factory

Friday, August 11, 2017

Part 45 - Display record from database using Jquery DataTables plugin




In this video you will be able to display data from DATABASE using jquery datatable plugin . before starting anything, please download latest version of Jquery DataTable. Click here to download the latest version of Jquery Datatable.  You can watch my previous tutorial to get step by step DataTable plugin installation guide. you can visit here: Integrate JQuery DataTable plugin into Asp.net MVC 

The expected output will be as what displayed in following image. 


# View Page (Index.cshtml)

Right click on your controller' s Index method and add a view. After adding view, replace content with below code. 

<div class="col-md-9">
        <table class="display" id="MyDataTable">
            <thead>
                <tr>
                    <th>
                        EmaployeeName
                    </th>
                    <th>
                        Department
                    </th>
                    <th>
                        Address
                    </th>
                    <th>
                        EmployeeId
                    </th>
                </tr>
            </thead>

            <tbody></tbody>

        </table>

    </div>

<script>

        $(document).ready(function () {

            // $("#MyDataTable").DataTable();

            GetEmployeeRecord();
        })
        var GetEmployeeRecord = function () {

            $.ajax({

                type: "Get",
                url: "/Test/GetEmployeeRecord",
                success: function (response) {

                    BindDataTable(response);

                }
            })

        }


        var BindDataTable = function (response) {

            $("#MyDataTable").DataTable({

                "aaData": response,
                "aoColumns": [

                    { "mData": "Name" },
                    { "mData": "DepartmentName" },
                    { "mData": "Address" },
                    { "mData": "EmployeeId" },


                ]

            });
        }


</script>


  # ViewModel (EmployeeViewModel)
Create two table in database i.e. Employee and Department table. Insert few record into it. Then finally refresh your entity framework. Entity framework will automatically create Employee and Department class and if they are connected to each other then, You will see the virtual keyword referencing Department table in employee class.
 Create a class named EmployeeViewModel and add same property into it as present in Employee class created by entity framework.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }

        [Required(ErrorMessage = "Enter Name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Enter Department")]
        public Nullable<int> DepartmentId { get; set; }

        [Required(ErrorMessage = "Enter Address")]
        public string Address { get; set; }

        public Nullable<bool> IsDeleted { get; set; }

        //Custom attribute
        public string DepartmentName { get; set; }
        public bool Remember { get; set; }
        public string SiteName { get; set; }
       
    }
}

# Controller Code (TestController.cs)
Create a controller and add below method into it. 

  public JsonResult GetEmployeeRecord()
        {

            MVCTutorialEntities db = new MVCTutorialEntities();

            List<EmployeeViewModel> List = db.Employees.Select(x => new EmployeeViewModel
            {
                Name = x.Name,
                EmployeeId = x.EmployeeId,
                DepartmentId = x.DepartmentId,
                DepartmentName = x.Department.DepartmentName,
                Address=x.Address,
                IsDeleted = x.IsDeleted
            }).ToList();

            return Json(List, JsonRequestBehavior.AllowGet);

        }


All Code Factory

Thursday, August 10, 2017

Part 44 - Integrate JQuery DataTables plugin into Asp.Net MVC application




In this video you will be able to add jquery datatable plugin into your project and to know how to use it. You just need to download latest version of Jquery DataTable . Click here to download the latest version of Jquery Datatable
After downloading the latest version, add the .css , .js file and images into your project as shown in above video. In the next step, include the DataTable.js and DataTable.css file reference into Layout Page. The expected output will be as what displayed in following image. 


 # View Page (Index.cshtml)

 Add below code in your Index page

</div>
    <table class="display" id="MyDataTable">
        <thead>
            <tr>
                <th>
                    EmaployeeName
                </th>
                <th>
                    Department
                </th>
                <th>
                    Salary
                </th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td>John</td>
                <td>CSE</td>
                <td>52000</td>
            </tr>
            <tr>
                <td>Sara</td>
                <td>EC</td>
                <td>52000</td>
            </tr>

         
        </tbody>

    </table>
<script>

    $(document).ready(function () {

        $("#MyDataTable").DataTable();
    })

</script>



All Code Factory

Saturday, July 15, 2017

Part 42 - How to implement JQuery Autocomplete Textbox with data from server in Asp.net MVC application


In this video you will be able to implement JQuery-UI Autocomplete Textbox with data from server side. Autocomplete feature used to display suggestion while we type into textbox. 
For implementing this, you need to download latest version of Jquery UI . Click here to download the latest version of Jquery-UI
The latest version will only be compatible with higher version of Jquery i.e.  Jquery 1.7+ .
After downloading the latest version, add the .css , .js file and images into your project. In case if you find any problem the follow the  steps as shown in the above video.

#Controller Code
Add a controller named "Test" and replace everything with below code. In below code, you will find three methods
a) Index () : This method will return view.
b) GetSuggestion(string text) : This method will return the JSON list of items matching with the parameter value.

using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{

    public class TestController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }


        [HttpGet]
        public JsonResult GetSuggestion(string text)
        {
            List<MyShop> ItemList = new List<MyShop>();

            ItemList.Add(new MyShop { ItemID = 1, ItemName = "Rice", IsAvailable = true });
            ItemList.Add(new MyShop { ItemID = 2, ItemName = "Pulse", IsAvailable = false });
            ItemList.Add(new MyShop { ItemID = 3, ItemName = "Salt", IsAvailable = false });
            ItemList.Add(new MyShop { ItemID = 4, ItemName = "Sugar", IsAvailable = true });
            ItemList.Add(new MyShop { ItemID = 5, ItemName = "Soap", IsAvailable = false });
            ItemList.Add(new MyShop { ItemID = 6, ItemName = "Book", IsAvailable = true });
            ItemList.Add(new MyShop { ItemID = 1, ItemName = "Apple", IsAvailable = true });
            ItemList.Add(new MyShop { ItemID = 2, ItemName = "Aeroplane", IsAvailable = false });
            ItemList.Add(new MyShop { ItemID = 1, ItemName = "Orange", IsAvailable = true });
            ItemList.Add(new MyShop { ItemID = 2, ItemName = "Boy", IsAvailable = false });
            ItemList.Add(new MyShop { ItemID = 1, ItemName = "Blackberry", IsAvailable = true });
            ItemList.Add(new MyShop { ItemID = 2, ItemName = "Lewis", IsAvailable = false });
            ItemList.Add(new MyShop { ItemID = 1, ItemName = "Women", IsAvailable = true });
            ItemList.Add(new MyShop { ItemID = 2, ItemName = "C++", IsAvailable = false });


            List<string> list = new List<string>();

            list = ItemList.Where(x => x.ItemName.ToLower().Contains(text.ToLower())).Select(x => x.ItemName).ToList();


            return Json(list, JsonRequestBehavior.AllowGet);
        }



    }
}
  

 # View Page (Index.cshtml)

Right click on your controller' s Index method and add a view. After adding view, replace content with below code.  

@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">


    <div class="col-md-9">
        <h4>Technotips MVC tutorial</h4>
              
        <input type="text" class="form-control" id="textAutocomplete" />

    </div>

</div>

<script>

    //var autoSuggestionArray = ["Ashish", "Apple", "Orange", "Boy", "Girl"]

    $("#textAutocomplete").autocomplete({

        source: function (request, response) {
            var text = $("#textAutocomplete").val();

            $.ajax({
                type: "GET",
                url: "/Test/GetSuggestion",
                data: { text: request.term },
                success: function (data) {

                    response($.map(data, function (item) {

                        return { lable: item, value: item }

                    }))


                }

            })

        }
    });





All Code Factory

Part 41 - How to create responsive sortable image gallery using Jquery-UI



In this video you will be able to create responsive sortable photo gallery. for that you need to download latest version of Jquery UI . Click here to download the latest version of Jquery-UI
The latest version will only be compatible with higher version of Jquery i.e.  Jquery 1.7+ .
After downloading the latest version, add the .css , .js file and images into your project. In case if you find any problem the follow the  steps as shown in the above video. The expected output will be as what displayed in following image. 
Our main objective is that, we have to sort the sequence of the below image by dragging and dropping method. For that we can use the .sortable() method offered by JQuery-UI 





 # View Page (Index.cshtml)

Right click on your controller' s Index method and add a view. After adding view, replace content with below code.  
Please follow below points: 
1. Please take an equal size of images or else you can set equal height and width for all images. 
2. Make sure to replace below images with your images.
3. Don't forget to give reference of JQuery-UI  .jss , .css file reference into your layout page


<div class="panel panel-body" style="min-height:256px">
  
    <div class="col-md-9">
        <h4>Technotips MVC tutorial</h4>

        <ul class="list-group" id="SortableGallery" style="cursor:move">
            <li class="list-group-item col-md-4" >
                <div>
                    <img class="img-responsive" src="~/Content/images/vocal.jpg" />
                </div>
            </li>
            <li class="list-group-item col-md-4">
                <div>
                    <img class="img-responsive" src="~/Content/images/voiline.jpg" />
                </div>
            </li>
          
            <li class="list-group-item col-md-4">
                <div>
                    <img class="img-responsive" src="~/Content/images/tabla.jpg" />
                </div>
            </li>
            <li class="list-group-item col-md-4">
                <div>
                    <img class="img-responsive" src="~/Content/images/social.jpg" />
                </div>
            </li>
            <li class="list-group-item col-md-4">
                <div>
                    <img class="img-responsive" src="~/Content/images/onlinebookstore.jpg" />
                </div>
            </li>
            <li class="list-group-item col-md-4">
                <div>
                    <img class="img-responsive" src="~/Content/images/mobile.jpg" />
                </div>
            </li>
        </ul>

    </div>

</div>

<script>

    $("#SortableGallery").sortable({

        update: function () {

            alert("Wow");
        }
    });

</script>


All Code Factory

Saturday, March 18, 2017

Part 37 - Implementing search functionality using jquery and partial view in Asp.net mvc



#Expected Output 





#Controller Code(TestController.cs)


using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {

        public ActionResult Index()
        {
            MVCTutorialEntities db = new MVCTutorialEntities();

            List<EmployeeViewModel> list = db.Employees.Select(x => new EmployeeViewModel { Name = x.Name, EmployeeId = x.EmployeeId, DepartmentName = x.Department.DepartmentName, Address = x.Address }).ToList();

            ViewBag.EmployeeList = list;

            return View();
        }

        public ActionResult GetSearchRecord(string SearchText)
        {

            MVCTutorialEntities db = new MVCTutorialEntities();


            List<EmployeeViewModel> list = db.Employees.Where(x => x.Name.Contains(SearchText) || x.Department.DepartmentName.Contains(SearchText)).Select(x => new EmployeeViewModel { Name = x.Name, EmployeeId = x.EmployeeId, DepartmentName = x.Department.DepartmentName, Address = x.Address }).ToList();

            return PartialView("SearchPartial", list);


        }

    }
}

  
#Model (EmployeeViewModel.cs) 


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCTutorial.Models
{
    public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public Nullable<int> DepartmentId { get; set; }
        public string Address { get; set; }
        public Nullable<bool> IsDeleted { get; set; }
        //Extra attribute
        public string DepartmentName { get; set; }
        public bool Remember { get; set; }
        public string SiteName { get; set; }
       
    }
}

 # View (Index.cshtml)


@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">

    <div class="col-md-3">

        @*@{ Html.RenderAction("SideMenu", "Test");}*@

    </div>
    <div class="col-md-9">
        @Html.TextBoxFor(m => m.Name, new { @class="form-control",@placeholder="Search here"})
        <img src="~/Content/loading.gif" id="loader" height="20" width="20" style="display:none"/>

        <table class="table table-striped">
            <tr>
                <th>
                    Name
                </th>
                <th>
                    DepartmentName
                </th>
                <th>
                    Address
                </th>
                <th>
                    Action
                </th>
            </tr>
            <tbody id="employeeRow">

                @if (ViewBag.EmployeeList != null)
                {
                    foreach (var item in ViewBag.EmployeeList)
                    {
                        <tr>
                            <td>@item.Name</td>
                            <td>@item.DepartmentName</td>
                            <td>@item.Address</td>
                            <td><a href="#"><i class="glyphicon glyphicon-eye-open"></i>View</a></td>
                        </tr>

                    }

                }

            </tbody>
        </table>

    </div>

</div>

<script>

    $(document).ready(function () {

        $("#Name").keydown(function () {
            $("#loader").show();
            var searchtext = $(this).val();
            debugger
            $.ajax({

                type: "Post",
                url: "/Test/GetSearchRecord?SearchText=" + searchtext,
                contentType: "html",
                success: function (response) {                   
                    $("#loader").hide();

                    $("#employeeRow").html(response);

                }

            })

        })

    })

</script>

 # Partial View (SearchPartial.cshtml)


@model IEnumerable<MVCTutorial.Models.EmployeeViewModel>

@if (Model != null)
{
    foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.DepartmentName</td>
            <td>@item.Address</td>
            <td><a href="#"><i class="glyphicon glyphicon-eye-open"></i>View</a></td>
        </tr>

    }
}

 #Database Script (MVCTutorial > Employee Table ) 


USE [MVCTutorial]
GO
/****** Object:  Table [dbo].[Employee]    Script Date: 19-03-2017 00:02:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
 [EmployeeId] [int] IDENTITY(1,1) NOT NULL,
 [Name] [varchar](50) NULL,
 [DepartmentId] [int] NULL,
 [Address] [varchar](150) NULL,
 [IsDeleted] [bit] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
 [EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [FK_Employee_Department] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Department] ([DepartmentId])
GO
ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Department]
GO

 

All Code Factory