How to call sub onchange of a dropdownlist while using AJAX?

1.9k Views Asked by At

So, I know how to call a method onclick of a button using ajax, but I'd like to do the same when a user selects something new on a dropdownlist. I'll show code for what I've tried below:

<asp:UpdatePanel ID="pnlHelloWorld" runat="server">

      <ContentTemplate>

        <div style="height: auto; overflow: auto; max-height:750px; width:100%;">
          <asp:DropDownList ID="mydropdownlist" runat="server" Enabled="true" OnChange="changeMyTable"></asp:DropDownList>   
          <asp:Table ID="mytable" runat="server"></asp:Table>
        </div>

      </ContentTemplate>

</asp:UpdatePanel>

In the page's aspx.vb:

Private Sub changeMyTable()
'Add rows to table
end sub

The problem is that "changeMyTable" is undefined when i change the dropdownlist.

How can I do this?

1

There are 1 best solutions below

1
Mahesh On BEST ANSWER

You are using the OnChange event to call the code behind method from javascript. To access the code behind method you need to convert that method to the WebMethod. For that below is something you can try (Just an example)

     <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
     <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
     <asp:TextBox ID="txtMsg" runat="server"></asp:TextBox>

Javascript code -

   <script type="text/javascript">
    function greet(txtN, txtLastN, txtMsg){
     var ctrlN = document.getElementById(txtN);
     var ctrlLastN = document.getElementById(txtLastN);
     var fullName = ctrlN.value + '  ' + ctrlLastN.value;
     PageMethods.greetUser(fullName, greetSuccess, greetFailed, txtMsg);
   }
  function greetSuccess(res, txtMsg) {
    var ctrlTxtMsg = document.getElementById(txtMsg);
    ctrlTxtMsg.value = res;
   }
  function greetFailed(res, dst) {
    alert(res.get_message());
   }
 </script>

Code behind method -

   <System.Web.Services.WebMethod()> _
      Public Shared Function greetUser(ByVal fullName As String) As String
         Return "Welcome " & fullName & "!"
     End Function

Now you can call your javascript function greet from wherever you want and it will trigger the code behind method greetUser. More on this is available here.