ASP.NET-在刷新页面后保持下拉列表中所选值的状态,而不使用viewstate和autopostback

ASP.NET - Keeping the state of the selected value of the dropdown after refreshing the page without using viewstate and autopostback

本文关键字:状态 autopostback viewstate 刷新 NET- 下拉列表 ASP      更新时间:2023-09-26

我使用的是ASP.NET下拉框,并已将javascript函数连接到"OnChange"事件。

该函数实际上将控件重定向回服务器中的页面加载函数,并刷新页面。我不应该将autopost-back属性设置为true。

我想确保在刷新页面后,下拉列表中包含选定的值。

我应该使用任何隐藏的变量吗?或者asp.net中是否有一个属性可以帮助我实现这一点?

任何帮助都将不胜感激。感谢

我的代码看起来像这样。。

<asp:DropDownList ID="CountriesDropDown" Width="100" runat="server" OnChange = "Send(this);"/>
function Send(dropdown)
{
//Should I write any code here ? 
refreshpage(); //separately implemented to redirect the url back to server
}
In server side
PageLoad()
{
CountriesDropDown.DataSource = CountriesList;
ContriesDropDown.DataBind();
//are there any properties that I could use so that the drop-down retains the selected value ?

}

根据刷新页面的方式:

  • GET:您必须将选定的值添加到URL参数中
  • POST:您应该使用隐藏字段并在Request.Params[yourHiddenField.UniqueID]中获取其值

在您的下载列表被绑定后执行此操作。

我应该使用任何隐藏的变量吗?或者asp.net中有属性吗能帮我做到这一点吗?

是的。Viewstate在ASP.Net中可以帮助您实现这一点。但是,你不想用它!

现在您可以做的是在函数refreshpageonchange处理程序中添加一个包含所选选项的查询字符串:

function Send($dropdown) {
    //Should I write any code here ? 
    refreshpage(dropdown); //separately implemented to redirect the url back to server
}
function refreshpage($dropdown) {
    window.location = "MyPage.aspx?value=" + $dropdown.val();
}

现在,在代码隐藏页面中,首先检查名为"value"的查询字符串参数是否可用。如果是,那么在数据绑定之后将其设置为您选择的值。

MyAspDropDown.DataBind()
MyAspDropDown.SelectedValue = Request.Querystring("value")

尝试使用更新面板控件。

请结账http://msdn.microsoft.com/en-us/library/bb399001(v=vs.100).aspx