简体   繁体   English

使用AJAX时如何调用下拉列表的子onchange?

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

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. 因此,我知道如何使用ajax在按钮的onclick上调用方法,但是当用户在下拉列表中选择新内容时,我想做同样的事情。 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: 在页面的aspx.vb中:

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

The problem is that "changeMyTable" is undefined when i change the dropdownlist. 问题是,当我更改下拉列表时,“ changeMyTable”未定义。

How can I do this? 我怎样才能做到这一点?

You are using the OnChange event to call the code behind method from javascript. 您正在使用OnChange事件从javascript调用方法背后的代码。 To access the code behind method you need to convert that method to the WebMethod . 要访问方法背后的代码,您需要将该方法转换为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 - JavaScript代码-

   <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 . 现在,您可以从任意位置调用javascript函数greet ,它将触发方法greetUser后面的代码。 More on this is available here . 有关更多信息, 请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM