Thursday, May 22, 2014

ASP.net: Everything is fine, but Autopostback is not working in cascading dropdownlist. Why?

Question:
ASP.net: Everything is fine, but Autopostback is not working in cascading dropdownlist. Why?

Check the following code:

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub ddlState_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        ddlCity.Items.Clear()
        ddlCity.Items.Add("Select City")
        Select Case ddlState.SelectedValue
            Case "MS"
                ddlCity.Items.Add("Aurangabad")
                ddlCity.Items.Add("Mumbai")
                ddlCity.Items.Add("Pune")
            Case "GU"
                ddlCity.Items.Add("Vadodara")
                ddlCity.Items.Add("Surat")
            Case "KA"
                ddlCity.Items.Add("Bangalore")
            Case "AP"
                ddlCity.Items.Add("Hyderabad")
        End Select
        
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
State:
    <asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
    <asp:ListItem Value="">Select State</asp:ListItem>
    <asp:ListItem Value="MS">Maharashtra</asp:ListItem>
    <asp:ListItem Value="GU">Gujrat</asp:ListItem>
    <asp:ListItem Value="KA">Karnataka</asp:ListItem>
    <asp:ListItem Value="AP">Andhra Pradesh</asp:ListItem>
    </asp:DropDownList>
City:
    <asp:DropDownList ID="ddlCity" runat="server">
    </asp:DropDownList>
    <asp:Button ID="submit" runat="server" Text="Button" />
    </form>
</body>
</html>



Answer:
There is some bug with asp.net when you use a button with Id="submit", it cancels Autopostback. Simply change Id="btnSubmit", Autopostback will start working.

<asp:Button ID="submit" runat="server" Text="Button" />

Change to

<asp:Button ID="btnSubmit" runat="server" Text="Button" />

Hope this helps you and saves your time.

No comments:

Post a Comment