K.Olagon K.Olagon - 3 years ago 245
Vb.net Question

How can I pass variable from jQuery to SelectCommand in SqlDataSource?

I'm trying to pass variable from jQuery to SqlDataSource in dropdownlist.

First, the jQuery's variable get the value from asp:dropdownlist_1 then keep it in the variable in jquery.

Next step, I would like to send the jquery's variable to SelectCommand in dropdownlist_2. Is it possible ?

If you have a good idea, it will be a great honor if you share it to me.

Thank you in advance

This is my ASPX markup:

<asp:DropDownList ID="DropDown_1" runat="server" CssClass="form-control"
DataSourceID="SqlDataSource_1"
DataTextField="field_1" DataValueField="field_2"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource_1" runat="server"
ConnectionString="<%$ ConnectionStrings:asrsDBConnectionString %>"
SelectCommand="SELECT * FROM [table_1]"></asp:SqlDataSource>

<asp:DropDownList ID="DropDown_2" runat="server" CssClass="form-control"
DataSourceID="SqlDataSource_2" DataTextField="field_1"
DataValueField="field_2"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource_2"unat="server"
ConnectionString="<%$ ConnectionStrings:asrsDBConnectionString %>"
SelectCommand="SELECT * FROM [table_2] WHERE [variable_from_jquery] = "value_JQ"></asp:SqlDataSource>


This is my Javascript code:

$('#<%:DropDown_1.ClientID %>').change(function () {
var value_JQ = $('#<%:DropDown_1.ClientID%>').val();
return value_JQ;
});

Answer Source

It is potentially possible to set some (hidden) input via jQuery and then use it.
But there is no need in such sophisticated approach. Apply KISS principle (Keep It Simple Stupid). Everything can be done in .aspx declaratively. Something like this.

<%--AutoPostBack="true" is important here --%>
<asp:DropDownList runat="server" ID="lstCountry" DataSourceID="sqlCountry" 
    DataTextField="CountryName" DataValueField="CountryId" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource runat="server" ConnectionString='<%$ConnectionStrings:MyCNN %>' ID="sqlCountry"
    SelectCommand="select CountryId,CountryName from dbo.Countries" />

<asp:DropDownList runat="server" ID="lstState" DataSourceID="sqlState" 
    DataTextField="StateName" DataValueField="StateId">
</asp:DropDownList>
<asp:SqlDataSource runat="server" ConnectionString='<%$ConnectionStrings:MyCNN %>' ID="sqlState"
    SelectCommand="select StateId,StateName from dbo.States where CountryId=@CountryId" >
    <SelectParameters>
        <%--Take parameter value from 1st dropdown --%>
        <asp:ControlParameter Name="CountryId" ControlID="lstCountry" 
            PropertyName="SelectedValue" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

No more code required.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download