【发布时间】:2015-05-02 01:15:49
【问题描述】:
我动态创建了一个下拉列表。我需要动态添加onchange 事件并进行回发,以便进行数据库调用。当我更改下拉列表项时,我收到错误:
ReferenceError: UpdateLocationList 未定义。
这是我的 javascript 代码:
<head runat="server">
<title>Locations</title>
<meta http-equiv="Content-Language" content="en-us"/>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<script src = "scripts/jquery-1.11.2.min.js" type = "text/javascript"></script>
<script type="text/javascript">
function UpdateLocationList(obj) {
alert('In function');
var facilityValue = document.getElementById("FacilityTypeDDL").value;
alert(facilityValue);
__doPostBack('FacilityTypeDDL', facilityValue);
}
</script>
</head>
<body>
<%ListLocations()%>
</body>
这是后面代码中的 ListLocations() 方法:
Public Sub ListLocations()
Response.Write("<div style='text-align:left;'>")
Response.Write("<label>Facility Type:<select id='FacilityTypeDDL' name='FacilityTypeDDL' size='1' runat='server' onchange='UpdateLocationList(this)'>")
For Each facility As ListItem In lstBoxFacilityTypes
'Get the first value in the list and use the ID to to the list of locations below
If String.Compare(facilityValueSelected, "") = 0 Then
facilityValueSelected = facility.Value
End If
Response.Write("<option value=''" & facility.Value & "''>" & facility.Text & "</option>")
Next
Response.Write("</select></label>")
Response.Write("</div>")
Response.Write("<hr>")
End Sub
缺少什么会导致函数 UpdateLocationList 未定义的错误?
更新 我直接将下拉列表作为 asp:DropDownList:
添加到了 aspx 页面 <body>
<form id="form1" runat="server">
<div style='text-align:center;'>
<a style='text-decoration:none;font-size:16px;color:blue;background-color:white;width:200px;padding:4px;' href='LocationDetails.aspx?Location_ID=0' target='detailPanel'> Add Location
</a></div>
  
<asp:Label ID="FacilityTypeLbl" runat="server">Facility Type:</asp:Label>
<asp:DropDownList ID="FacilityTypeDDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged=" FacilityTypeDDL_SelectedIndexChanged">
</asp:DropDownList>
<hr/>
<%ListLocations()%>
</form>
</body>
在后面的代码中添加 OnSelectedChanged 事件:
Protected Sub FacilityTypeDDL_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles FacilityTypeDDL.SelectedIndexChanged
strFacilityValue = FacilityTypeDDL.SelectedValue
ListLocations()
End Sub
我在这个方法中设置了一个断点,它并没有在其中停止。 为什么我的事件没有触发?
【问题讨论】:
-
看起来您正在制作自定义 DropDownList 服务器控件。你正在做的方式真的很脆弱。你想达到什么目的?
-
这个控件没有任何自定义。它是动态的。我正在添加到现有的应用程序。单击按钮时,它会创建一个新菜单。这就是网站的工作方式。它有什么脆弱之处?
-
这不是我们在 ASP.Net 中创建动态控件的方式(除非您正在使用 MVC)。 ASP.Net 是一个基于事件的模型;你不想直接操作 DOM。简而言之,您想使用服务器控件并将其动态添加到占位符(或面板)。
-
我不知道如何重写这部分应用程序来完成你所说的。我只是想添加到当前的应用程序中。
标签: javascript asp.net