使用 Javascript / JQuery 从代码隐藏更新下拉列表



我有一个包含两个部分的应用程序。

顶部有一个dropdownlist,它使用代码隐藏方法在page load调用时显示database中的所有成员。

底部有一个网格,您可以在其中使用 JQuery add / delete / edit成员。此部分中的更改显然不会重建顶部的下拉列表。

我想在JQuery成功方法中运行一些代码,updates/rebuilds dropdownlist以反映对成员的最新更改。 如果可能的话,我想使用与page_load上的数据库相同的代码隐藏方法来populate下拉列表。

这可能吗? 如果是这样,我将如何实现这一目标?

任何帮助将不胜感激。

[请求的代码]
.aspx文件

<asp:DropDownList ID="director" runat="server"></asp:DropDownList> 
 jQuery success() fired on add/delete/update member grid.

.aspx.cs(代码隐藏)

private void LoadDirectorOptions(int deptId)  
{
            var memberRepo = new MemberRepository();  
            List<Member> members = memberRepo.GetMembers(deptId);
            director.DataSource = members;
            director.DataTextField = "FullName";
            director.DataValueField = "Id";
            director.DataBind();
            director.Items.Insert(0, new ListItem("<Please Select>", "0")); 
}

您不能使用相同的代码隐藏方法,因为它是服务器端代码,并且JQuery代码发生在客户端,除非您在执行JQuery代码后刷新页面。您可以在为更新网格而提供的同一 Web 服务上抓取所有成员。

向下列表。例如:

  $.ajax({
      // Updating the grid here and retrun all the members : it will be saved in the response
      type: "Get",
      url: url,
      data: data,
      dataType: dataType,
      success: success(data)
    });
    function success(data)
    {
      //here you can get the resposne from the server
      // Iterate through data and add option elements
      $(".members").append("<option value=? text=?/>");
    }

很可能您的数据必须JSON具有服务器成员数据库表中的所有成员。 然后,您可以将CSS类(成员)添加到下拉列表中JQuery并使用选择器选择下拉列表。

希望这是有帮助的。

应该在成功调用调用方法中使用 ajax。 http://api.jquery.com/jQuery.ajax/

如果要刷新下拉列表而不刷新整个页面,则需要将它们包装在UpdatePanel中。更改底部的网格时,更新 UpdatePanel 以重新绑定下拉列表。要强制 UpdatePanel 在 Javascript 中更新,您可以使用 GetPostBackEventReference 方法强制回发,如下所示:

<%= Page.ClientScript.GetPostBackEventReference(updatePanelID, "")%>

最新更新