1

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?

4

1 回答 1

2

您正在使用该OnChange事件从 javascript 调用方法背后的代码。要访问方法背后的代码,您需要将该方法转换为WebMethod. 因为下面是你可以尝试的东西(只是一个例子)

     <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代码 -

   <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>

方法背后的代码 -

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

现在你可以从任何你想要的地方调用你的javascript函数greet,它会触发方法后面的代码greetUser。更多信息可在此处获得

于 2015-02-09T06:32:03.633 回答