Thursday, April 18

How to Bind State by Selecting Country DropDownList using WebMethod in Asp.net

Introduction:-
                 In this article I have explained  how to bind a dropdownlist using Ajax.
Description:-
               Some developers binding the dropdownlist directly in pageload.which will give low performance to your site.Now a days every user wants to avoid unnecessary postbacks during any events.Lets take a common example that  I want to bind a state list according to the country selection. I can do it in code behind selectedindexchange event,but it will result performance issue as discussed previously,so I will prefer to use ajax here.


 To get the result you have to follow the following steps, here you can see the source code where I have explained the ajax call.
<div class="Internaldiv1">
<div class="Lable_">
Country :
</div>
<div class="Text_Long">
<asp:DropDownList ID="ddlCountry" onChange="GetStates()" CssClass="d_down" runat="server"
Style="width: 255px;">
</asp:DropDownList>
</div>
</div>
<asp:RequiredFieldValidator ID="validate_Country" runat="server" ErrorMessage="Select Country"
Text="*" ForeColor="Red" ControlToValidate="ddlCountry" InitialValue="0" SetFocusOnError="true" Display="None"
ValidationGroup="y"></asp:RequiredFieldValidator>
<div class="Internaldiv1">
<div class="Lable_">
State :
</div>
<div class="Text_Long">
<asp:DropDownList ID="ddlState" CssClass="d_down" runat="server" Style="width: 255px;">
<asp:ListItem Value="">Select State</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<asp:RequiredFieldValidator ID="validate_State" runat="server" ErrorMessage="Select State" Display="None"
Text="*" ForeColor="Red" ControlToValidate="ddlState" SetFocusOnError="true"
ValidationGroup="y"></asp:RequiredFieldValidator>
Here is My Javascript method GetStates()
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#txtDOB").datepicker({ dateFormat: 'dd/mm/yy' });
    });
    $(document).ready(function () {
        $("#<%=ddlState.ClientID%>").change(function () {
            //I have stored dropdowlist value in a hidden field because during postback it wont
            //loose the value(not neccessery)
            $("#<%=hdn_State.ClientID%>").val($("#<%=ddlState.ClientID%>").val());
        });
    });
    //This method i have used here
    var ddlState;
    function GetStates() {
        var ddlCountry = document.getElementById("<%=ddlCountry.ClientID%>");
        ddlState = document.getElementById("<%=ddlState.ClientID%>");
        var Values = ddlCountry.options[ddlCountry.selectedIndex].value;
        //PageMethods.BindState(Value, OnSuccess);
        $.ajax({
            type: "POST",
            url: "Default.aspx/BindState",
            //data: data,
            data: "{ 'Values': '" + Values + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                debugger;
                $("#<%=ddlState.ClientID %>").empty();
                $("#<%=ddlState.ClientID %>").empty().append($("<option></option>").val("--Select--").html("-Select State-"));
                $.each(response.d, function () {
                    $("#<%=ddlState.ClientID %>").append($("<option></option>").val(this['Value']).html(this['Text']));
                });
                return true;
            },
            error: function () {
                alert("An error has occurred during processing your request.");
                jQuery("#ddlState").empty();
                jQuery("#ddlState").empty().append(jQuery("<option></option>").val("--Select--").html("-Select State-"));
            }
        });
    }

Here is My
Code Behind WebMethod Default.aspx/BindState
public void BindCountry()
{
EDAUBO obj = new EDAUBO();
obj.Operation = "SelectCountry";
List<EDAUBO> dtCountry = new List<EDAUBO>();
EDAUBAL objBAL = new EDAUBAL();
dtCountry = objBAL.SelectCountry(obj);
var Countryinfo = from n in dtCountry select n;
ddlCountry.DataSource = Countryinfo.ToList();
ddlCountry.DataTextField = "Country_Name";
ddlCountry.DataValueField = "Country_ID";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, "Select Country");
ddlCountry.Items[0].Value = "0";
}
[WebMethod]
public static ArrayList BindState(int Values)
{
ArrayList list = new ArrayList();
try
{
EDAUBO obj = new EDAUBO();
obj.Operation = "SelectState";
EDAUBAL objBAL = new EDAUBAL();
List<EDAUBO> dtState = new List<EDAUBO>();
dtState = objBAL.SelectState(obj);
var dtStateData = from n in dtState where n.Country_ID == Values select n;
for (int i = 0; i < dtState.Count(); i++)
{
list.Add(new ListItem(dtStateData.ToList()[i].State_Name.ToString(), dtStateData.ToList()[i].State_ID.ToString()));
}
}
catch (Exception ex)
{
}
return list;
}
I hope this article will help the developers who always preferring code behind method instead of Ajax.Now a days ajax is the best approach for a developer.
Keep coding.......
 
Thanks Shibashish Mohanty
 

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty