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 display alert message from code behind file in asp.net ?


Hi

There are so many approaches to display alert message from code behind file i.e by vb.net and C#. But one of the easiest ways to display alert message using Ajax ScriptManager like this

Write code on buttonclick event like this


 protected void Button1_Click(object sender, EventArgs e)
    {
        // Here will be your some conditional code
        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Data has been added Sucessfully');", true);
    }

How to check EmailId availability on clientside using WCF and Ajax ?


EmailAvailability

Hi
So many time while creating registration page we will get scenario to check EmailId availability in database. We can do this using so many ways. But if we will do using direct c# code behind approach then full post-back will happen. So it will make so slow.

We can do this task using WCF and Ajax scriptmanager control on client side without any postback.

Step1: Create Ajax Enable WCF service like this. I hope your are knowing all the basis stuff to do this task.

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 System.Data;
using System.Data.SqlClient;

[ServiceContract(Namespace = "")]
[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 string CheckEmailId(string emailID)
    {
        string status = string.Empty;
        // Add your operation implementation here
        using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
        {
            using (SqlCommand cmd = new SqlCommand("Select EmailId from tblEmail where EmailId=@EmailId", con))
            {
                cmd.Parameters.AddWithValue("@EmailId", emailID);
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    status = "Available";
                }
                else
                {
                    status = "Not Available";
                }
                return status;

            }
        }
    }

	
}


Step 2: Consume the Service using ScriptManager in aspx page like this

Step 3: Call the WCF method using Javascript like this

function EmailIdCheck() {
Service.CheckEmailId(document.getElementById(‘txtEmailId’).value, onSuccess, null, null);

}

function onSuccess(result) {

// $get(“lblmsg”).innerHTML = result;
if(result == ‘Available’)
{
// Img1.src = tick.png;
var imgDisplay = $get(“imgDisplay”);
imgDisplay.src = “tick.png”;
imgDisplay.style.display = “block”;
$get(“lblmsg”).innerHTML = “Sorry this EmailId has been taken.”;
$get(“lblmsg”).style.color = “green”;
}
else {
// Img1.src = unavailable.png;
var imgDisplay = $get(“imgDisplay”);
imgDisplay.src = “unavailable.png”;
imgDisplay.style.display = “block”;
$get(“lblmsg”).innerHTML = “Not Available”;
$get(“lblmsg”).style.color = “red”;
}

}

Step 4: On aspx Textbox onblur event call the javascript method like this

Now you can validate the EmailId on client side using this few steps

Here is the complete .aspx code

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

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

    <script language="javascript" type="text/javascript">
        function EmailIdCheck() {
            Service.CheckEmailId(document.getElementById('txtEmailId').value, onSuccess, null, null);
           
        }

        function onSuccess(result) {

            // $get("lblmsg").innerHTML = result;
            if(result == 'Available')
            {
                // Img1.src = tick.png; 
                var imgDisplay = $get("imgDisplay");
                imgDisplay.src = "tick.png";
                imgDisplay.style.display = "block";
                $get("lblmsg").innerHTML = "Sorry this EmailId has been taken.";
                $get("lblmsg").style.color = "green";
            }
            else {
                //  Img1.src = unavailable.png;
                var imgDisplay = $get("imgDisplay");
                imgDisplay.src = "unavailable.png";
                imgDisplay.style.display = "block";
                $get("lblmsg").innerHTML = "Not Available";
                $get("lblmsg").style.color = "red";
            }

        }

</script>

    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 276px;
        }
        .style3
        {
            width: 102px;
        }
        .style4
        {
            width: 144px;
        }
        .style5
        {
            width: 19px;
        }
    </style>

</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <br />
        <table class="style1">
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    Email Id:&nbsp;&nbsp;</td>
                <td class="style4">
                    <asp:TextBox ID="txtEmailId" onblur="EmailIdCheck();"  runat="server" />
                </td>
                <td class="style5">
                     <img id = "imgDisplay" alt="" src="" style = "display:none"/></td>
                <td>
                     <asp:Label ID="lblmsg" runat="server"/> </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    &nbsp;</td>
                <td class="style4">
                    &nbsp;</td>
                <td class="style5">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    EmpName:</td>
                <td class="style4">
                    <asp:TextBox ID="txtName" runat="server" />


     
       

                </td>
                <td class="style5">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2">

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
        <asp:ServiceReference Path="~/Service.svc" />
        </Services>
        </asp:ScriptManager>


                </td>
                <td class="style3">
                    &nbsp;</td>
                <td class="style4">
                    &nbsp;</td>
                <td class="style5">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>

    </div>
    </form>
</body>
</html>


.

How to display latest twitter post in website ?


Twitter1

Hi
Before ajax 4.0 it very difficult to display latest twitter post on website. But in ajax 4.0, now one separate control has been added and it is very simple to use in the project. Just drag and drop the control and give the ScreenName.

 <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

    <asp:Twitter ID="Twitter1" ScreenName="Chandradev819" runat="server">
    </asp:Twitter>

.

How to use Masked Edit ajax validator control for Date ?


Mask

If we have to validate Textbox for Date format then “Ajax Masked Edit” control is one of the easiest solution to do this task. We can do 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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Image ID="Image1" ImageUrl="~/Calendar_scheduleHS.png" runat="server" />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <asp:MaskedEditExtender   
            ID="MaskedEditExtender1"  
            runat="server"  
            TargetControlID="TextBox1" 
            Mask="99/99/9999"   
            MaskType="Date" 
           CultureName="en-US" 
            MessageValidatorTip="true"/>  
     
         
        <asp:MaskedEditValidator   
            ID="MaskedEditValidator1"  
            runat="server"  
            ControlToValidate="TextBox1"  
            ControlExtender="MaskedEditExtender1"  
            IsValidEmpty="false"/>  
    
        <asp:CalendarExtender ID="CalendarExtender1" TargetControlID="TextBox1" format="dd/MM/yyyy"  PopupButtonID="Image1" runat="server"/>
        <br />
    </div>
    </form>
</body>
</html>