考虑 .ASPX 文件中的单行标记,如下所示:
<asp:DropDownList ID="drpdownPayPlan" runat="server" onchange="javascript: document.getElementById('txtPayAmount').value = document.getElementById('drpdownPayPlan').value.replace(',', '');">
我可以保留我的嵌入式 JavaScript 处理程序代码吗?如何保留?我知道将 WebForms 应用程序移植到 ASP.NET MVC 时还有很多其他问题,但我想保持简单并只关注这一行。目前,我在这一行收到的错误是:
Unhandled exception at line 410, column 115 in http://localhost:3835/Policy/QuotePayments?QN=XYZ-1234567&PN=ABCDEFGHIJ&AC=123456789
0x800a138f - JavaScript runtime error: Unable to get property 'value' of undefined or null reference
渲染后,源代码实际上在第 410 行读取如下(我理解名称损坏的原因):
<select name="ctl00$MainContent$drpdownPayPlan" id="MainContent_drpdownPayPlan" onchange="javascript: document.getElementById('txtPayAmount').value = document.getElementById('drpdownPayPlan').value.replace(',', '');">
所以,恕我直言——没有给我讲道如何正确地将 WebForms 项目移植到 MVC(抱歉,听起来像一个叛逆且不合作的青少年!)——我该如何解决我遇到的问题用这一行标记?
最佳答案
0x800a138f
当尝试分配服务器端控件名称(由于默认服务器控件行为分配 AutoID
,该名称在客户端中不存在)而不是客户端名称时,ASPX 页面中经常会发生错误,因此 document.getElementById('drpdownPayPlan')
返回undefined
.
有两种方法可以解决:
分配
ClientIDMode="Static"
涉及到的每个服务器控件(我假设txtPayAmount
是TextBox
服务器控件,如果您使用文字输入文本框,则保留txtPayAmount
不变)。<asp:TextBox ID="txtPayAmount" runat="server" ClientIDMode="Static" /> <asp:DropDownList ID="drpdownPayPlan" runat="server" ClientIDMode="Static" onchange="javascript: document.getElementById('txtPayAmount').value = document.getElementById('drpdownPayPlan').value.replace(',', '');">
注意:
ClientIDMode
该属性在 .NET 4.0 及更高版本中可用。使用
<%= drpdownPayPlan.ClientID %>
引用客户端 ID,同时将控件 ID 保留在AutoID
中状态(我再次假设txtPayAmount
是一个TextBox
控件,如果txtPayAmount
是文字文本框,则保留它)。<asp:DropDownList ID="drpdownPayPlan" runat="server" onchange="javascript: document.getElementById('<%= txtPayAmount.ClientID %>').value = document.getElementById('<%= drpdownPayPlan.ClientID %>').value.replace(',', '');">
请注意,我建议您将 JS 部分与服务器控件分开,并在函数中调用函数名称,如下所示:
<asp:DropDownList ID="drpdownPayPlan" runat="server" onchange="changePayAmount();">
<script type="text/javascript">
function changePayAmount() {
document.getElementById('<%= txtPayAmount.ClientID %>').value = document.getElementById('<%= drpdownPayPlan.ClientID %>').value.replace(',', '');
}
</script>
PS:在 MVC 上下文中,id
对于每个 HTML 帮助器元素,都可以在 HTML 属性部分中轻松定义,如下所示:
@Html.DropDownListFor(model => model.PayPlan, Model.PayPlanList as SelectList, new { id = "drpdownPayPlan" })
类似问题:
0x800a138f - JavaScript runtime error: Unable to get property 'value' of undefined or null reference
JavaScript runtime error: Unable to get property 'value' of undefined or null reference
关于javascript - 如何在移植到 ASP.NET MVC 的 Web 表单页面中顽固地保留旧的 JavaScript 事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43266124/