我是ASP.NET新手,工作中遇到问题,请帮忙。
我想动态地将选项添加到 ASP 页面的下拉列表中。 所以我写了一个javascript函数:
<body>
<form id="form1" runat="server" style="height:100%">
</form>
<script type="text/javascript">
function addOptionToSelect(optKey, optValue) {
var select = document.getElementById('<%=mySelect.ClientID%>');
var opt = new Option(thisLabel, thisValue);
select.add(opt);
}
}
</script>
</body>
由于某些原因,我必须在 ASP 的代码隐藏中添加下拉列表 Web 控件:
protected void Page_Load(object sender, EventArgs e)
{
Table t = new Table();
form1.Controls.Add(t);
TableRow r = new TableRow();
formatTable.Rows.Add(r);
TableCell c = new TableCell();
formatRow.Cells.Add(c);
DropDownList select = new DropDownList();
select.ID = "mySelect";
select.Text = "mySelect:";
c.Controls.Add(select);
}
我会得到错误:
编译器错误消息:CS0103:当前上下文中不存在名称“mySelect”。
但是,如果我直接在ASP页面中添加下拉列表,就没有错误。
<form id="form1" runat="server" style="height:100%">
<div>
<asp:DropDownList ID="a_content_type" runat="server">
</asp:DropDownList>
</div>
</form>
我应该如何解决这个错误? “在 ASP 页面中添加 ASP Web 控件”和“在代码隐藏中添加 ASP Web 控件”有什么区别?
最佳答案
我想我可以找到另一种方法来解决这个问题。首先,我在 ASP header 中添加一个新函数:
function setClientID(id) { this.clientID = id; }
然后,在创建下拉列表后将以下代码添加到代码隐藏中:
Page.ClientScript.RegisterStartupScript(this.GetType(), "setClientID", "setClientID('" + mySelect.ClientID + "');", true);
最后,用“this.ClientID”替换“<%=mySelect.ClientID%>”。 它有效。
关于javascript - 当我使用 javascript 更改代码隐藏中创建的控件时,会发生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18253663/