gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:21:54 24 4
gpt4 key购买 nike

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

我有一个只包含一个 *.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com