Asp.Net: Restoring client-side SelectedItem of DropDownList on server-side

折月煮酒 提交于 2019-12-13 05:04:41

问题


So I have a dropDownList on my page that contains hundreds of items. The user can filter this DDL by typing some text into a textbox. The DDL then gets filtered accordingly (all items that do not contain the entered text are removed via JavaScript). The user then selects his item and presses a button. Usually, this would cause an error because the DDL has been altered and ASP validates the PostBack data. However, with EnableEventValidation="false" you can turn off this behavior and the page gets submited properly. But (and thats my problem): the SelectedIndex of the DDL is always "0" on server-side and thus the SelectedItem is the wrong one. So obviously, the changes on client-side are dismissed. Does anybody have an idea on how to get the correct SelectedItem? Or a better way to filter a DDL and maintain the correct SelectedItem?


回答1:


When user presses a button get current value of dropdown using jQuery and set it in hidden field on page , give hidden field runat="server" so that when it posts back you will get value that was selected. For example

    <asp:DropDownList class="myList"></asp:DropDownList>
    <asp:Button class="btn"/> 
    <input type="hidden" id="hdnSelectedI" runat="server" class="hiddenControl"> 

    $(document).ready(function(){

    $(".btn").click(function(){

      var selectedItem = $(".myList").val();
      $(".hiddenControl").val(selectedItem);  

    });

});

I have used clas name selector as ids in aspnet are auto generated. On server side get value of hdnSelectedItem.Value , and from that pull from list of items/db maintained on server.



来源:https://stackoverflow.com/questions/24558382/asp-net-restoring-client-side-selecteditem-of-dropdownlist-on-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!