我有两个选择用作国家/州的下拉列表
一切都按我的预期工作,但是当我进行回发时,我丢失了上面 <select...>
中的值保留值(value)观的最佳方法是什么?您能给我举个例子吗?
<asp: Button ID="Button1" runat="server"
onclick="Button1_Click" Text="PostBack" />
谢谢。
最佳答案
如果您将 ASP.NET 与某些 jQuery 一起使用,则可以在回发中设置隐藏字段的值。然后在 $(document).ready() 中,您只需从隐藏字段中读取该值。
在你的代码后面:
protected void Button1_Click(object sender, EventArgs e)
{
this.countryField.Value = "WhateverValueYouWantToPersist";
}
在您的 aspx 文件中:
$(document).ready(function(){
var persistedValue = <% this.countryField.ClientID %>;
// do something...
});
<asp:HiddenField runat="server" ID="countryField" />
更新:
我想出了一个更好的解决方案。我希望您只想捕获从选择列表中选择的值,而不需要保留整个国家/州集合。
我会这样设置我的 aspx 页面:
<asp:DropDownList runat="server" ID="countryField" />
<asp:DropDownList runat="server" ID="stateField" />
<asp:Button runat="server" ID="button1" OnClick="button1_click" OnClientClick="return clientSideClick()" />
<asp:HiddenField runat="server" ID="hiddenCountry" />
<asp:HiddenField runat="server" ID="hiddenState" />
在我的 jQuery 中,我将有一个函数来处理该单击,它捕获所选值并设置隐藏字段的值:
function clientSideClick() {
var state = $("#<%= this.stateField.ClientID %> :selected").val();
$("#<%= this.hiddenState.ClientID %>").val(state);
var country = $("#<%= this.countryField.ClientID %> :selected").val();
$("#<%= this.hiddenCountry.ClientID %>").val(country);
}
然后在服务器端按钮回发事件中,您可以捕获隐藏状态的值并从那里执行您需要执行的操作:
protected void button1_click(object sender, EventArgs e)
{
string stateValue = this.hiddenState.Value;
string countryValue = this.hiddenCountry.Value;
}
如果您确实想要重新选择之前选择的国家/地区对,那么在您的 jQuery 代码使用 ajax 例程加载国家/地区和州之后,之前选择的值仍将位于该隐藏字段中,您可以使用值来自那里。
关于javascript - 有没有办法保存值(value)观? - 在回发中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2670327/