Bootstrap模态框中选择ListBox后更新TextBox的问题
解决Bootstrap模态框中ListBox回发导致关闭的问题
嘿,我完全懂你碰到的这个糟心事——ASP.NET的ListBox开了AutoPostBack之后,整页回发直接把Bootstrap模态框给弄没了,刚选好的东西还没来得及处理呢!别慌,咱们有两个实用的解决办法,看你需求选:
方案一:纯前端JavaScript处理(无回发,最简单)
如果你的需求只是把ListBox的选中值同步到TextBox,完全不需要服务器端做额外处理,那直接用前端JS搞定就好,彻底避开回发问题:
- 把ListBox的
AutoPostBack设为false,关掉自动回发 - 给ListBox添加
onchange事件,触发同步逻辑 - 写一段JS函数获取选中值并赋值给TextBox
示例代码:
ASPX页面部分
<asp:ListBox ID="ListBox1" runat="server" onchange="syncListBoxToTextBox()"></asp:ListBox> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
JavaScript部分
function syncListBoxToTextBox() { // 获取ListBox的客户端ID(ASP.NET会自动生成,用<%= %>输出) var listbox = document.getElementById('<%= ListBox1.ClientID %>'); // 单选的情况:获取选中项的value或text if (listbox.selectedIndex !== -1) { var selectedValue = listbox.options[listbox.selectedIndex].value; var selectedText = listbox.options[listbox.selectedIndex].text; // 把值赋值给TextBox,选value或者text看你需求 document.getElementById('<%= TextBox1.ClientID %>').value = selectedValue; // 要是想显示文本就用这个:document.getElementById('<%= TextBox1.ClientID %>').value = selectedText; } // 要是ListBox是多选模式,就用下面这段循环获取所有选中项 // var selectedValues = []; // for (var i = 0; i < listbox.options.length; i++) { // if (listbox.options[i].selected) { // selectedValues.push(listbox.options[i].value); // } // } // document.getElementById('<%= TextBox1.ClientID %>').value = selectedValues.join(', '); }
方案二:用UpdatePanel实现局部回发(需要服务器端处理时用)
如果你必须要在服务器端处理ListBox的选中事件(比如从数据库取关联数据再赋值给TextBox),那可以用ASP.NET的UpdatePanel来做局部回发,这样只会刷新指定区域,不会影响模态框的状态:
ASPX页面代码
<div id="modalBillOLMapping" class="modal colored-header" style="display:none" > <div class="md-content"> <div class="modal-header"> <button type="button" data-dismiss="modal" aria-hidden="true">×</button> <h3 class="modal-title">你的模态框标题</h3> </div> <div class="modal-body"> <!-- 把需要回发的控件放到UpdatePanel里 --> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"></asp:ListBox> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </ContentTemplate> <!-- 配置异步回发触发器,指定ListBox的选中事件 --> <Triggers> <asp:AsyncPostBackTrigger ControlID="ListBox1" EventName="SelectedIndexChanged" /> </Triggers> </asp:UpdatePanel> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> </div> </div> </div>
后台C#代码
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { // 这里可以做任何服务器端逻辑,比如查询数据库 // 然后把选中值赋值给TextBox TextBox1.Text = ListBox1.SelectedValue; // 要是需要显示文本就用:TextBox1.Text = ListBox1.SelectedItem.Text; // 手动触发UpdatePanel更新(可选,因为UpdateMode设为Conditional时需要) UpdatePanel1.Update(); }
用这个方案的话,模态框会一直保持打开状态,只有UpdatePanel内部的内容会刷新,完美解决回发导致关闭的问题!
内容的提问来源于stack exchange,提问作者Rani Radcliff
相关产品推荐
相关产品推荐

