ASP中JS获取DropDownList值时出现Null错误,求解决方案
错误成因分析
- 服务器控件ID的客户端渲染差异:ASP.NET中带
runat="server"的服务器控件,最终输出到前端的HTML元素ID会被自动重写(比如如果控件在母版页、Panel等命名容器内,ID会变成类似ctl00_Content_Locations的格式)。你JS里用服务器端定义的Locations去查找元素,自然找不到,返回null,读取value时就触发了Cannot read properties of null的错误。 - 快速验证方式:按F12打开浏览器开发者工具,切换到Elements面板,找到下拉框对应的
<select>元素,查看它的id属性,就能发现和你JS里写的Locations完全不一样。
解决办法
- 方法1:用ASP.NET内置的ClientID输出正确ID
修改JS中的获取代码,让ASP.NET自动渲染出正确的客户端ID:function redirect() { var location = document.getElementById('<%= Locations.ClientID %>').value; window.open('/../Direct/NewPage.aspx?Location=' + location, 'List', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no, width=990,height=600,left=530,top=200'); } - 方法2:设置控件ClientIDMode为Static(ASP.NET 4.0+可用)
修改DropDownList的服务器端代码,强制客户端ID和服务器端ID保持一致:
这样你的原有JS代码不需要改动就能正常工作。<asp:DropDownList runat="server" ID="Locations" Width="40%" Autopostback="true" ClientIDMode="Static"></asp:DropDownList> - 方法3:通过类选择器定位元素
给DropDownList添加一个CSS类,用类选择器来获取元素:
服务器端代码:
JS代码修改为:<asp:DropDownList runat="server" ID="Locations" Width="40%" Autopostback="true" CssClass="location-dropdown"></asp:DropDownList>function redirect() { var location = document.querySelector('.location-dropdown').value; window.open('/../Direct/NewPage.aspx?Location=' + location, 'List', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no, width=990,height=600,left=530,top=200'); }
内容的提问来源于stack exchange,提问作者gbm0102
相关产品推荐
相关产品推荐

