Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Saturday, 23 December 2017

Dropdown with Multi Select (Multiple selection) with checkbox using jQuery, Bootstrap and Multiselect JS

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) with dropdown (select option in html) using CheckBox with help of jQuery, Bootstrap and MultiSelect JS.

In HTML File

In html file, create a select list (dropdown) with multiple="multiple" and bind with some dummy data as shown below.
Here in script JS files, First file is jQuery file Second, Third is bootstrap JS, CSS files and Fourth, Fifth file is MultiSelect JS and CSS Files.
Make sure all files is loaded when application runs.

Share:

Friday, 22 December 2017

DatePicker or Calendar Control in ASP.NET MVC using jQuery UI

In this tutorial, I am going to explain you how to attach DatePicker or Calendar control in ASP.NET MVC using jQuery UI. I will be using Visual Studio 2013. Below is step by step tutorial.

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Installing jQuery UI using Nuget (Compulsory)

Next step is to install jQuery.UI. Right click on References and go to Manage NuGet Packages as shown below.

Manage NuGet Packages in ASP.NET MVC

After that a new window will open as shown below. Search for jQuery.UI and install it.

Installing jQuery.UI in ASP.Net Mvc

After successful installation, you can see all css files related to datepicker are installed inside Content folder and and jquery-ui file is installed inside Scripts folder.

After successfull installation of jQuery.UI in ASP.Net Mvc

Installing Bootstrap and Unobtrusive jQuery (Optional)

If bootstrap js,css and Unobtrusive jQuery is not install in your application then you can install using nuget package manager.
Bootstrap: It is used for CSS and responsive design.
Unobtrusive jQuery: It is to make data annotation work at client machine.

Installing Bootstrap and Unobtrusive jQuery in ASP.Net Mvc

Adding Models

Go to Models folder and add new class file Employee.cs. Now replace all code with below code.

Share:

Sunday, 22 October 2017

ASP.NET ListBox with Multi Select DropdownList with CheckBoxes Using jQuery

In this tutorial, I am going to explain you how to implement multiple selection (MultiSelect) with ListBox control using CheckBox in ASP.NET with help of jQuery, Bootstrap and MultiSelect JS.

In ASPX File

In aspx file, create a ListBox control with SelectionMode="Multiple" and bind with some dummy ListItem data as shown below.
Here in script JS files, First is jQuery file and Second, Third is bootstrap JS and CSS files and Fourth and Fifth file is MultiSelect JS and CSS Files.
Make sure all files is loaded when application runs.
Here includeSelectAllOption is set to true to include Select All text at first position in Select List.

Share:

Saturday, 22 July 2017

Check uncheck or select deselect CheckBox using jQuery with GridView in ASP.NET

In this article, I am going to explain you, how to check and uncheck all checkboxes using jQuery in asp.net gridview. If header row checkbox is checked then all row checboxes should be checked and if any of row checkbox is unchecked then header checkbox should be unchecked.

DOWNLOAD SOURCE CODE
check uncheck or select deselect all checkboxes using jQuery
check uncheck or selectde select all checkboxes using jQuery in gridview

Data Source

To bind gridview, we need to have some dummy data. Below is the script to create table and insert data into it. Script is attached inside download source code folder.

create table tblStudent
(
Id int primary key identity,
Name varchar(50),
Gender varchar(10),
Marks int,
City varchar(50)
)
go
insert into tblStudent values('Rahul', 'Male', 10, 'Mumbai')
insert into tblStudent values('John','Male', 15,'London')
insert into tblStudent values('Mathew','Male', 20,'Sydney')
insert into tblStudent values('Mary','Female', 25,'Delhi')
insert into tblStudent values('Mithum','Male', 30,'Delhi')
insert into tblStudent values('Sara','Female', 35,'London')
insert into tblStudent values('Rahul','Male', 40,'Mumbai')
insert into tblStudent values('John','Male', 45,'London')
insert into tblStudent values('Mathew','Male', 50,'Sydney')
insert into tblStudent values('Mary','Female', 55,'Delhi')
insert into tblStudent values('Mithum','Male', 60,'Delhi')
insert into tblStudent values('Sara','Female', 65,'London')
insert into tblStudent values('Rahul','Male', 70,'Mumbai')
insert into tblStudent values('John','Male', 75,'London')
insert into tblStudent values('Mathew','Male', 80,'Sydney')
insert into tblStudent values('Mary','Female', 85,'Delhi')
insert into tblStudent values('Mithum','Male', 90,'Delhi')

Design GridView

In aspx file, create a gridview control as shown below. In the first TemplateField, there are two check-boxes chkHead and chkRow.

<div style="margin-top: 25px; margin-left: 250px;">
    <asp:GridView ID="grdStudent" runat="server" DataKeyNames="Id" CellPadding="5" 
       AutoGenerateColumns="false" Width="540px" OnPageIndexChanging="grdStudent_PageIndexChanged" 
       AllowPaging="true" PageSize="5">
        <AlternatingRowStyle BackColor="White" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <RowStyle HorizontalAlign="Center" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Left" />
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkHead" runat="server"></asp:CheckBox>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server"></asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Gender">
                <ItemTemplate>
                    <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Marks">
                <ItemTemplate>
                    <asp:Label ID="lblMarks" runat="server" Text='<%#Eval("Marks") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code-Behind File

In code-behind file, bind gridview control using dummy data from database as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;//namespace added
using System.Configuration;//namespace added
using System.Data.SqlClient;//namespace added

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }

        private void BindGrid()
        {
            DataSet ds = null;
            SqlConnection con = null;
            try
            {
                con = new SqlConnection(ConnString);
                SqlCommand cmd = new SqlCommand("select * from tblStudent", con);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                ds = new DataSet();
                sda.Fill(ds);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    grdStudent.DataSource = ds.Tables[0];
                    grdStudent.DataBind();
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    grdStudent.DataSource = ds;
                    grdStudent.DataBind();
                    grdStudent.Rows[0].Visible = false;
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }

        protected void grdStudent_PageIndexChanged(object sender, GridViewPageEventArgs e)
        {
            grdStudent.PageIndex = e.NewPageIndex;
            BindGrid();
        }
    }
}

jQuery Code

First we need to add jQuery file to our application. We can either download latest jQuery file from http://jquery.com/download/ and put jQuery file into Script folder of our application or we can directly use CDN links in code as shown below.
Code to load jQuery Framework from Google CDN

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Code to load jQuery Framework from Microsoft CDN
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>

I am using downloaded jQuery file as shown below and below is the complete jQuery code to select and deselect check-boxes.

<head runat="server">
  <title></title>
  <script src="Scripts/jquery-3.0.0.js" type="text/javascript"></script>
  
  <script type="text/javascript" language="javascript">
    $(document).ready(function () {

      //this code will be executed on click of header row checkbox
      $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").click(function () {

        //check if header row checkbox is checked and store into variable
        var flag = $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").is(':checked');

        //find all row checkboxes: if flag == true then set attribute checked=true or if flag == false then set checked=false
        $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").prop('checked', flag);

      });

      //this code will be executed on click of data row checkbox
      $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").click(function () {

        //count total number of row checkboxes
        var rowCheckboxesCount = $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").length;

        //count total number of row checkboxes which are checked
        var rowCheckboxesCheckedCount = $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox:checked").length;

        // if counts are same that means:  total number of row checkboxes == total number of row checkboxes which are checked
        // then find header row checkbox and set to true or false
        $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").prop('checked', rowCheckboxesCount == rowCheckboxesCheckedCount);

      });

    });
  </script>
</head>
Share:

Monday, 26 June 2017

Cascaded Dropdown in ASP.Net MVC using Entity Framework and jQuery ajax

In this article, I am going to teach you the basic cascading Dropdown in ASP.Net MVC using Entity Framework and jQuery Ajax. So, I am going to use Visual Studio 2013 ultimate, .net framework 4.5 and MVC version 4 and below is step by step tutorial.

Creating Database Table

First of all, we need to create database table. Below is the script to create two tables that are State Master and District Master and insert some dummy data into it.

create table tblStateMaster
(
StateId int,
Name varchar(100)
)
go
insert into tblStateMaster values(1,'Maharashtra')
insert into tblStateMaster values(2,'Gujarat')
go
create table tblDistrictMaster
(
DistId int,
StateId int,
Name varchar(100)
)
insert into tblDistrictMaster values(1,1,'Mumbai')
insert into tblDistrictMaster values(2,1,'Thane')
insert into tblDistrictMaster values(3,1,'Pune')
insert into tblDistrictMaster values(4,1,'Raigad')
go
insert into tblDistrictMaster values(5,2,'Ahmedabad')
insert into tblDistrictMaster values(6,2,'Rajkot')
insert into tblDistrictMaster values(7,2,'Gandhinagar')
insert into tblDistrictMaster values(8,2,'Vadodara')
Create table

Creating ASP.Net MVC Application

Now we need to create asp.net mvc application. Open Visual Studio 2013. Go to File --> New --> Project.. as shown below.

Creating a new asp.net mvc application

Go to Installed --> Templates --> Web --> Visual Studio 2012 and select .NET Framework 4.5 and ASP.NET MVC 4 Web Application as shown below.

Selecting asp.net mvc project

In the next window, select Empty template and click on OK and new MVC project will be created as shown below

Selecting asp.net mvc templateAsp.net mvc folder architecture

Adding Entity Framework

Now the next step is Entity Framework. Go to TOOLS --> Library Package Manager --> Manage NuGet Packages for Solution.. and a new window will open. Type and search for Entity Framework and click on Install button as shown below. Once installed successfully, you can check Entity Framework in references folder.

Adding Entity Framework
Installing Entity Framework

Adding Model

Now the next step is to add model. Go to Model and add two class files i.e. Data.cs and DataContext.cs. In Data.cs file, add below lines of code to map our database table to model object.

Adding modelAdding model and context class
[Table("tblStateMaster")]
public class State
{
    [Key]
    public int StateId { get; set; }
    public string Name { get; set; }
}

[Table("tblDistrictMaster")]
public class District
{
    [Key]
    public int DistId { get; set; }
    public int StateId { get; set; }
    public string Name { get; set; }
}

In DataContext.cs file, add two properties of type DbSet which will return DbSet of State and District.

Adding context class
public class DataContext : DbContext
{
    public DbSet<State> State { get; set; }
    public DbSet<District> District { get; set; }
}

Adding Connection String

Now add the connection string as shown below. Name of connection string should be same as context class name[DataContext].

Adding web.config file
Data context and web.config file connection string

Adding Controller

Now the next step is to add controller. Go to controller folder and add a new controller file named as DropDownController. Add below lines of code.

Adding controller class
public class DropDownController : Controller
{
    DataContext dc = new DataContext();

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

    public JsonResult GetState()
    {
        var stateData = dc.State.ToList().OrderBy(x => x.Name);
        return Json(stateData, JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetDistrict(int StateId)
    {
        var districtData = dc.District.Where(x => x.StateId == StateId).OrderBy(x => x.Name);
        return Json(districtData);
    }
}

Adding jQuery File

Now the next step is to add jQuery file. You can download latest jQuery file from http://jquery.com/download/. Add jQuery file to your Scripts folder.

Adding View

Now the next step is to add View. Right click on Index ActionResult method, click Add View, give your View name as Index and do not click on strongly-typed view and click on Add. A DropDown folder will be added inside Views folder and an Index.cshtml file will be created.

Below is the code to Bind State Dropdown and District Dropdown using jQuery ajax method.

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">

    // bind State Dropdown when html is loaded
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/DropDown/GetState",
            datatype: "Json",
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlState').append('<option value="' + value.StateId + '">' + value.Name + '</option>');
                });
            }
        });
    });
    // bind State Dropdown when html is loaded

    // bind district Dropdown on selection change of State
    $(document).ready(function () {
        $('#ddlState').change(function () {
            $('#ddlDistrict').empty();
            $.ajax({
                type: "POST",
                url: "/DropDown/GetDistrict",
                datatype: "Json",
                data: { StateId: $('#ddlState').val() },
                success: function (data) {
                    $('#ddlDistrict').append('<option value>--Select--</option>');
                    $.each(data, function (index, value) {
                        $('#ddlDistrict').append('<option value="' + value.DistId + '">' + value.Name + '</option>');
                    });
                }
            });
        });
    });
    // bind district dropdownlist on Dropdown change of State
</script>

<h2>Cascading DropDownList Example</h2>
<table style="font-family:Arial;">
    <tr>
        <td>
            @Html.DropDownList("ddlState", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
        <td>
            @Html.DropDownList("ddlDistrict", new SelectList(string.Empty, "Value", "Text"), "--Select--", null)
        </td>
    </tr>
</table>

Once View is loaded successfully, you can see expected output below.

Cascading dropdown in asp.net mvc
Share:

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

Ads By Chitika