我在网络表单的Page_Load
方法中有以下代码:
protected void Page_Load(object sender, EventArgs e)
{
CountrySelectButton.Click += new EventHandler(CountrySelectButton_Click);
if (HomePage.EnableCountrySelector) //always true in in this case
{
if(!IsPostBack)
BindCountrySelectorList();
}
}
BindCountrySelectorList
方法如下所示:
private void BindCountrySelectorList()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(HomePage.CountryList);
var ds = nvc.AllKeys.Select(k => new { Text = k, Value = nvc[k] });
CountrySelector.DataSource = ds;
CountrySelector.DataTextField = "Text";
CountrySelector.DataValueField = "Value";
CountrySelector.DataBind();
}
我有一个LinkButton
点击事件处理程序,它从SelectedValue
获取SelectList
,如下所示:
void CountrySelectButton_Click(object sender, EventArgs e)
{
//get selected
string selectedMarket = CountrySelector.SelectedValue; //this is always the first item...
//set cookie
if (RememberSelection.Checked)
Response.Cookies.Add(new HttpCookie("blah_cookie", selectedMarket) { Expires = DateTime.MaxValue });
//redirect
Response.Redirect(selectedMarket, false);
}
修改
这是DDL和LinkButton的定义:
<asp:DropDownList runat="server" ID="CountrySelector" />
<asp:LinkButton runat="server" ID="CountrySelectButton" Text="Go" />
结果标记:
<select name="CountrySelector" id="CountrySelector">
<option value="http://google.com">UK</option>
<option value="http://microsoft.com">US</option>
<option value="http://apple.com">FR</option>
</select>
<a id="CountrySelectButton" href="javascript:__doPostBack('CountrySelectButton','')">Go</a>
结束编辑
ViewState已启用,但SelectedValue
属性仅返回列表中的第一个项目,而不管实际选择了哪个项目。我确定我错过了一些明显但我无法找到问题的东西;非常感谢任何帮助。
提前致谢。
戴夫
答案 0 :(得分:0)
将Button.Click = ...语句包裹在(!IsPostBack)中,如
if(!IsPostBack)
{
MyButton.Click += new EventHandler(MyButton_Click);
BindSelectList();
}
答案 1 :(得分:0)
你的问题源于jquery ui对话框是正确的...你可以通过使用隐藏字段记录下拉列表的值来解决这个问题。然后在您的代码中引用隐藏字段。
前端看起来像:
<div id="myModal" style="display: none;">
<asp:DropDownList runat="server" ID="SelectList" />
<asp:LinkButton runat="server" ID="MyButton" Text="Go" />
</div>
<input type="hidden" id="countryVal" runat="server" />
<a id="choose" href="#">Choose</a>
<script type="text/javascript">
$(document).ready(function () {
$('#choose').click(function () {
$('#myModal').dialog({
});
return false;
});
$('#<%= SelectList.ClientID %>').change(function () {
var country = $(this).val();
$('#<%= countryVal.ClientID %>').val(country);
});
});
</script>
然后你的代码落后:
var selected = countryVal.Value;