gpt4 book ai didi

c# - 控件 ascx 不存在

转载 作者:太空宇宙 更新时间:2023-11-03 12:30:58 26 4
gpt4 key购买 nike

我有一个具有以下结构的 Web 应用程序项目

ProjectName
-Controls
--WebControls
--MyControl.ascx

-CustomerControls
--CustDetails.ascx

在 CustDetails.ascx 控件中我试图加载 MyControl.ascx,所以我在页面上添加了一个引用(不是代码隐藏)即

<%@ Register Src="../Controls/WebControls/MyControl.ascx" TagPrefix="Ctrl" TagName="CustCtrol" %>

页面加载没有错误。

我现在将下面的代码添加到代码隐藏

LoadControl = Page.LoadControl("MyControl.ascx");

但我收到“文件‘/MyControl.ascx’不存在。”

我尝试将路径更改为

~/Controls/WebControls/MyControl.ascx

但同样的错误。改成了

../Controls/WebControls/MyControl.ascx

然后获取“无法使用前导 .. 退出顶级目录之上。

我已经尝试过各种变体并在谷歌上进行了搜索,但我无法理解哪里出了问题?

编辑 1

目录Directory Image的附加图片

最佳答案

注意这里的目录结构:

ProjectName

-Controls

--WebControls

--MyControl.ascx

它说 MyControl.ascx 在 Controls 目录中,而不是 WebControls。

你有两个选择:

1) 将 MyControl.ascx 移动到 WebControls 目录,重建解决方案,这些代码将起作用:

<%@ Register Src="~/Controls/WebControls/MyControl.ascx" TagPrefix="ctrl" TagName="CustControl" %>

LoadControl = Page.LoadControl("~/Controls/WebControls/MyControl.ascx");

2) 将其保存在您列出的同一目录中(Controls 目录中的 MyControl.ascx)并将上述代码中的路径更改为:

<%@ Register Src="~/Controls/MyControl.ascx" TagPrefix="ctrl" TagName="CustControl" %>

LoadControl = Page.LoadControl("~/Controls/MyControl.ascx");

无需使用 Server.MapPath。

此外,如果您在 MyControl 代码隐藏类中定义了公共(public)方法或属性,则需要将加载的控件强制转换为 MyControl 以便访问这些方法和属性,就像我在此处所做的那样:

LoadControl = Page.LoadControl("...") as MyControl;
//or
LoadControl = (MyControl)Page.LoadControl("...");

关于c# - 控件 ascx 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42808642/

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