.net - 从页面后面的代码调用用户控件中的函数

标签 .net asp.net user-controls .net-2.0 code-behind

现在这一切都简化了,但这里是:

我有一个只包含一个 *.ascx 文件的用户控件。该控件没有代码隐藏:它只是一个具有一些功能的脚本,如下所示:

<%@ Control Language="VB" EnableViewState="False" ClassName="MyControlType" %>
<script runat="server">
    Public Function MyFunction() As String
       return "CalledMyFunction!"
    End Function
</script>

这就是整个文件。我可以使用如下标记成功地将此控件添加到 aspx 页面:
<%@ Register Src="~/path/to/Control.ascx" TagPrefix="aaa" TagName="MyControl" %>
...
<aaa:MyControl runat="server" id="MyControl1" />

现在我想做的是从页面的代码隐藏中调用 MyFunction ,如下所示:
Dim someString As String = MyControl1.MyFunction()

不幸的是,我不能那样做。相反,我收到了“'MyFunction' is not a member of 'System.Web.UI.UserControl'.”的影响的编译错误

我也试过这个:
Dim someString As String = DirectCast(MyControl1, MyControlType).MyFunction()

然后编译器告诉我,“Type 'MyControlType' is not defined.

我已经玩了很多次,但我无法让它发挥作用。将 MyControl1 转换为更精确类型的所有努力都失败了,其他变通方法也是如此。我怀疑问题在于没有代码隐藏的 ascx 文件无法编译为程序集,但代码隐藏想要编译为程序集,因此编译器对控件的类型感到困惑。

我需要做什么才能调用该函数?

[编辑]
所以我只需要为用户控件添加代码隐藏。无论如何,这是我想做的。不过,我仍然想知道如何在不需要的情况下做到这一点。

最佳答案

奇怪的对我有用。

Imports Microsoft.VisualBasic

Public Class MyControlType
    Inherits UserControl
End Class

.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Src="~/WebUserControl.ascx" TagPrefix="aaa" TagName="MyControl"  %>
...
<aaa:MyControl runat="server" id="MyControl1"  />

.
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        Dim someString As String = MyControl1.MyFunction()
    End Sub

End Class

.
<%@ Control Language="VB" EnableViewState="False"  %>
<script runat="server">
    Public Function MyFunction() As String
       return "CalledMyFunction!"
    End Function
</script>

关于.net - 从页面后面的代码调用用户控件中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/360836/

相关文章:

c# - "asp-format"不适用于标签助手

asp.net - 多个用户一次分配了相同的 session ID

user-controls - 依赖属性 - 成员无法识别或无法访问

c# - 有没有办法用 ToolboxBitmap 实现真正的透明度?

C# 可移植类库 - 使用图像

.NET 项目/命名空间组织问题

c# - 将数据从 jQuery Ajax 发送到 MVC COntroller

asp.net - 如何在 Web 应用程序中实现时区?

.NET:ArrayList 与 List

c# - 将 Canvas 大小调整为相邻标签的文本高度