首页 > 解决方案 > VB 代码中无法访问 WebForms ScriptManager 标记

问题描述

我在以下位置有一个带有此标记的 aspx 页面<body>

<asp:ScriptManager ID="scriptManager1" runat="server" />

现在在 aspx 页面的其他地方,我有一些 VB 代码(使用嵌入在页面中<% %>,而不是在 vb 文件后面的代码中):

scriptManager1.RegisterClientScriptBlock(Me.GetType(), "mandatoryAdditionalFieldRules_ContactType", tempStr)

问题是,我在该行收到一个编译错误,说 scriptManager1 未声明。我认为所有控件runat="server"都可以在代码中访问?为什么这不起作用?

编辑:

哦,我想通了 - 有点。RegisterClientScriptBlockScriptManager出于某种原因的共享方法,所以我需要这样称呼它:

ScriptManager.RegisterClientScriptBlock(Me.GetType(), "mandatoryAdditionalFieldRules_ContactType", tempStr)

将其作为实例方法调用是行不通的。

但是 - 现在我收到一条错误消息,说 ScriptManager 类本身不存在!我在页面顶部引用了适当的命名空间:

<%@ Import Namespace="System.Web.UI" %>

为什么找不到 ScriptManager?如果我通过命名空间显式引用该类,我什至会得到一个错误:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.GetType(), "mandatoryAdditionalFieldRules_ContactType", tempStr)

编辑:这是一个应该重现错误的简单页面:

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="UTF-8" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.IO" %>
<html>
    <head>
        <title>FRED</title>
    </head>
    <body>
        <asp:ScriptManager ID="scriptManager1" runat="server" />
        <%
            System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.GetType(), "mandatoryAdditionalFieldRules_ContactType", "alert('fred');")
        %>
    </body>
</html>

编辑:按照建议尝试了这个,同样的错误:

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="UTF-8" %>

<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender
        System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.GetType(), "mandatoryAdditionalFieldRules_ContactType", "alert('fred');")
    End Sub
</script>
<html>
<head>
    <title>FRED</title>
</head>
<body>
    <asp:ScriptManager ID="scriptManager1" runat="server" />
</body>
</html>

标签: asp.netvb.netwebforms

解决方案


根据您尝试在方法调用中使用的参数,您看起来有点像是在混合两个单独的类:

System.Web.UI.ScriptManager

System.Web.UI.ScriptManager 文档链接

System.Web.UI.ClientScriptManager

System.Web.UI.ClientScriptManager 文档链接

这两个中的第一个生活在System.Web.Extensions.dll集会中。您是否检查过您正在引用此程序集?

第二个是通过类ClientScript上的属性公开的Page。我认为你应该做的是(注意 C# 语法,但应该很容易更改为 VB):

<%
    this.ClientScript.RegisterClientScriptBlock(this.GetType(), "mandatoryAdditionalFieldRules_ContactType", "alert('fred');");
%>

推荐阅读