每次在 Firefox 中“重新加载”页面(按下 F5)时,我如何将我的asp:DropDownList
元素(具有)重置为索引 0?runat="server"
如果您建议使用 JavaScript,请注意
- 我没有使用表格
- 我不知道如何访问
runat="server"
带有 JavaScript的元素
如果这可以使用.aspx
页面上的脚本完成,请解释。
每次在 Firefox 中“重新加载”页面(按下 F5)时,我如何将我的asp:DropDownList
元素(具有)重置为索引 0?runat="server"
如果您建议使用 JavaScript,请注意
runat="server"
带有 JavaScript的元素如果这可以使用.aspx
页面上的脚本完成,请解释。
将代码放入Page_Load事件中以执行此操作
protected void Page_Load(object sender, EventArgs e)
{
myDropDownList.SelectedIndex =0;
}
编辑:
作为对您的评论的回应,如果您已将上述逻辑放在 if 语句中以检查是否Page.IsPostback = false
,则所选索引将不会在刷新时设置回 0 (执行客户端回发)。作为演示这一点的示例,这里有一个下拉列表设置为在选择时自动回发的页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>My Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" >
</asp:DropDownList>
</div>
</form>
</body>
</html>
这是后面的代码
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
//Apologies for Dairy Produce inspired list
ddl.Items.Add(new ListItem("Cheese"));
ddl.Items.Add(new ListItem("Yoghurt"));
ddl.Items.Add(new ListItem("Milk"));
ddl.Items.Add(new ListItem("Butter"));
}
protected void Page_Load(object sender, EventArgs e)
{
//Run the Page with this in first, then comment out
//the if statement to leave only ddl.SelectedIndex = 0;
if (!Page.IsPostBack)
{
ddl.SelectedIndex = 0;
}
}
}
正如将要演示的,当页面最初运行时,刷新时,选定的索引将保留在下拉列表中;但是,当if
语句被注释掉时,在刷新时,选定的索引设置为 0(在本例中为Cheese)。
stop Firefox from retaining the viewstate and repopulating the form:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Browser.Browser == "Firefox")
Form.Attributes.Add("autocomplete", "off");
}
只需将此代码添加到您的 Page_Load 事件中:
if (myDropDown.Items.Count > 0)
{
myDropDown.Items[myDropDown.SelectedIndex].Selected = false;
myDropDown.Items[0].Selected = true;
}
在代码 HTML 下的脚本中:
B01 = document.getElementById('<%=me.yourID.clientid %>');
B01.selectedIndex = 0;
快乐编码^^