How to create Ajax cascading dropdown using Ajax enabled WCF ?


Cascading DDL

Hi

While working on web based project, we will get scenario to create cascading drop-down. But if there are more data and you are binding the drop-down using direct approach then performance will be very slow.

In Ajax toolkit there are Cascading drop-down control, using this control we can create very responsive and interactive cascading drop-down. It will give good performance.

Note: I suppose that you are knowing how to use ajax enable WCF in asp.net.

Here is very simple steps to do this task

Steps 1: Drag the Cascading Ajax Control from ajax toolkit and drop in your designer and configure the control like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <fieldset>
    <legend><b>Ajax Cascading Dropdown Demo</b></legend>
   <br />
    <table>
        <tr>
            <td style="width: 80px">
                Country:
            </td>
            <td>
                <asp:DropDownList ID="ddlCountries" runat="server" Width="150">
                </asp:DropDownList>
                <asp:CascadingDropDown ID="cdlCountries" TargetControlID="ddlCountries" PromptText="Select Country"
                    PromptValue="" ServicePath="Service.svc" ServiceMethod="GetCountries" runat="server"
                    Category="CountryId" LoadingText="Loading..." />
            </td>
        </tr>
        <tr>
            <td>
                State:
            </td>
            <td>
                <asp:DropDownList ID="ddlStates" runat="server" Width="150">
                </asp:DropDownList>
                <asp:CascadingDropDown ID="cdlStates" TargetControlID="ddlStates" PromptText="Select State"
                    PromptValue="" ServicePath="Service.svc" ServiceMethod="GetStates" runat="server"
                    Category="StateId" ParentControlID="ddlCountries" LoadingText="Loading..." />
            </td>
        </tr>
        <tr>
            <td>
                City:
            </td>
            <td>
                <asp:DropDownList ID="ddlCities" runat="server" Width="150">
                </asp:DropDownList>
                <asp:CascadingDropDown ID="cdlCities" TargetControlID="ddlCities" PromptText="Select City"
                    PromptValue="" ServicePath="Service.svc" ServiceMethod="GetCities" runat="server"
                    Category="CityId" ParentControlID="ddlStates" LoadingText="Loading..." />
            </td>
        </tr>
    </table>
     </fieldset>
    </form>
</body>
</html>


Step2 : Write the Ajax Enabled WCF code to fetch data from database on basis of categoryId


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using AjaxControlToolkit;
using System.Configuration;
using System.Data.SqlClient;

[ServiceContract(Namespace = "MyTestService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
	// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
	// To create an operation that returns XML,
	//     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
	//     and include the following line in the operation body:
	//         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
	[OperationContract]
    public List<CascadingDropDownNameValue> GetCountries(string knownCategoryValues)
    {
        string query = "SELECT CountryName, CountryId FROM Countries";
        List<CascadingDropDownNameValue> countries = GetData(query);
        return countries;
    }

    [OperationContract]
    public List<CascadingDropDownNameValue> GetStates(string knownCategoryValues)
    {
        // this will find the countryId
        string country = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["CountryId"];
        string query = string.Format("SELECT StateName, StateId FROM States WHERE CountryId = {0}", country);
        List<CascadingDropDownNameValue> states = GetData(query);
        return states;
    }

    [OperationContract]
    public List<CascadingDropDownNameValue> GetCities(string knownCategoryValues)
    {
        // this will find the StateId
        string state = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["StateId"];
        string query = string.Format("SELECT CityName, CityId FROM Cities WHERE StateId = {0}", state);
        List<CascadingDropDownNameValue> cities = GetData(query);
        return cities;
    }

    private List<CascadingDropDownNameValue> GetData(string query)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlCommand cmd = new SqlCommand(query);
        List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
        using (SqlConnection con = new SqlConnection(conString))
        {
            con.Open();
            cmd.Connection = con;
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    values.Add(new CascadingDropDownNameValue
                    {
                        name = reader[0].ToString(),
                        value = reader[1].ToString()
                    });
                }
                reader.Close();
                con.Close();
                return values;
            }
        }
    }
	
}


How to format Gridview rows on basis of data in asp.net ?


GridFormate
Hi

We can format asp.net gridview rows on basis of data using C# helper method like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class FormateFieldInGridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string FormatEmpSal(object objEmpSal) 
    {
        if (objEmpSal.Equals(DBNull.Value.ToString()))
        {
            return "<span style='color: red; font-weight: bold;'>EmpSal is Blank</span>";
        }
        else
        {
            decimal Sal = Convert.ToDecimal(objEmpSal);
            if (Sal <= 0)
            {
                return "<span style='color: red; font-weight: bold;'>EmpSal is Zero</span>";
            }
            else
            {
                return Sal.ToString();
            }
        }
    }
}

In aspx bind this method like this

FormateGridCode

How to do sorting in gridview on client side using Jquery ?


TableSortExp

Hi

We can do sorting in asp.net gridview using tablesorter jquery plugin. It will do soring of data in client side only. It is very simple to use in asp.net

Step1: Write the aspx code like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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">
 <title></title>
 <style type="text/css">
        th
        {
        	cursor:pointer;
        	background-color:#dadada;
        	color:Black;
        	font-weight:bold;
        	text-align:left; 
        }
        th.headerSortUp 
        {     
        	background-image: url(images/asc.gif);
        	background-position: right center;
        	background-repeat:no-repeat; 
        }
        th.headerSortDown 
        {     
        	background-image: url(images/desc.gif);   
        	background-position: right center;
        	background-repeat:no-repeat; 
        } 
        td
        {
            border-bottom: solid 1px #dadada;	
        }
    </style>
    <script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
    <script src="scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#GridView1").tablesorter();
        }); 
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" Width="312px" runat="server" CellPadding="4" 
            ForeColor="#333333" GridLines="Both"
            Font-Size="9pt" Font-Names="Arial" AutoGenerateColumns="False"
            BorderColor="#DADADA" BorderStyle="Solid" BorderWidth="1px" 
            DataKeyNames="EmpId" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="EmpId" HeaderText="EmpId" InsertVisible="False" 
                    ReadOnly="True" SortExpression="EmpId" />
                <asp:BoundField DataField="EmpName" HeaderText="EmpName" 
                    SortExpression="EmpName" />
                <asp:BoundField DataField="EmpSal" HeaderText="EmpSal" 
                    SortExpression="EmpSal" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:EmpDBConnectionString %>" 
            SelectCommand="SELECT * FROM [tblEmp]"></asp:SqlDataSource>
    </div>
    </form>
</body>
</html>


Step 2: Write the code in page load like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.UseAccessibleHeader = true;
        GridView1.HeaderRow.TableSection = TableRowSection.TableHeader; 
    }
}

Note: Please download the above plugin to test this code.

How to implement quick search jquery plugin in asp.net ?


QuickSearch
Hi

Jquery quick search plugin is very interactive and nice plugin. Just now i implemented in one of my project. It will do very nice way interactive search without any postback. It will do search functionality on client side only.

For implementing this plugin in asp.net is very simple.

Step 1: Take one repeater control and configure like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableViewState="false" %>

<!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">
  <title>quickSearch Test</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <script src="jquery-1.2.6.min.js" type="text/javascript"></script>
  <script src="jquery.quicksearch.js" type="text/javascript"></script>
  <script src="Helper.js" type="text/javascript"></script>
</head>

<body>
  <form id="form1" runat="server">
  <asp:Repeater runat="server" ID="EmpDetails">
    <HeaderTemplate>
      <table id="EmpDetails">
        <thead>
          <tr>
            <th>EmpName</th>
            <th>EmpSal</th>
          </tr>
        </thead>
        <tbody>
    </HeaderTemplate>
    
    <ItemTemplate>
      <tr>
       <td>
          <asp:Repeater ID="Repeater1" runat="server" datasource='<%# Eval("EmpName") %>'>
            <ItemTemplate><%# Container.DataItem %></ItemTemplate>
          </asp:Repeater>
        </td>
        <td><%# Eval("EmpSal") %> </td>
      </tr>
    </ItemTemplate>
    
    <FooterTemplate>
      </tbody> </table>
    </FooterTemplate>
  </asp:Repeater>
  </form>
</body>
</html>

Step 2: Write the Helper javascript file like this



$(document).ready(function() {
    $("#EmpDetails tbody tr").quicksearch({
    // label for displaying Search Field.
    labelText: 'Search By EmpName: ',
    
    // Anchor the search form to the table 
    //  and position it before the table
    attached: '#EmpDetails',
    position: 'before',
    
    // React quickly to keypresses.
    delay: 100,
    
    // Eliminate the "loader".
    loaderText: '',
    
    onAfter: function() {
        if ($('#EmpDetails tbody tr:visible').length == 0) {
        // No Items.  Do something fancy here.
      }
    }
  });
});

Step 3: Write the code to populate the repeater control like this.


using System;
using System.Linq;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=EmpDB;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("Select *from tblEmp", con))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                EmpDetails.DataSource = dt;
                EmpDetails.DataBind();
            }
        }
    }
}

I hope it will be useful to somebody.

How to find the duplicate value in array using Javascript ?


Hi

While working on asp.net project, So many time we will get scenario to check the duplicate input value like on textbox value. We can do like this.


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
    <script type="text/javascript">

    function testValues() {
        var no1 = document.getElementById('<%= TextBox1.ClientID %>').value;
        var no2 = document.getElementById('<%= TextBox2.ClientID %>').value;
        var no3 = document.getElementById('<%= TextBox3.ClientID %>').value;
        var no4 = document.getElementById('<%= TextBox4.ClientID %>').value;
        var arrInput = [no1,no2,no3,no4];
        var sorted_arr = arrInput.sort(); 
        var results = [];
        for (var i = 0; i < arrInput.length - 1; i++) {
            if (sorted_arr[i + 1] == sorted_arr[i]) {
                results.push(sorted_arr[i]);
            }
        }

        alert("duplicate Value:  " + results);
    }

    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <asp:TextBox ID="TextBox1" runat="server" />
    <br />
    <asp:TextBox ID="TextBox2" runat="server" />
    <br />
    <asp:TextBox ID="TextBox3" runat="server" />
    <br />
    <asp:TextBox ID="TextBox4" runat="server" />
    <br />
    <br />
    <asp:Button ID="Button1" Text="Submit" OnClientClick="testValues();" runat="server" />
</asp:Content>