【C#】找不到在ObjectDataSource的TypeName屬性中指定的型別
2020-12-11 C#
由於要求,所有網站.cs檔案都儲存在App_Code目錄中,並編譯為App_Code.dll。
當我嘗試訪問網站的特定頁面時出現錯誤。
Description: An unhandled exception occurred during the execution
of the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The type
specified in the TypeName property of ObjectDataSource
'DataSourceSubmissionList' could not be found.
我有一個由ObjectDataSource填充的Gridview控制元件。程式碼如下:
/layouts/Portal/Company/Application/code.ascx:
<%@ Control Language="c#" AutoEventWireup="true"
CodeFile="~/layouts/Portal/Company/Application/code.ascx.cs"
Inherits="Project.WebUserControls.myapplications.sublayout" %>
<dx:ASPxGridView ID="ASPxGridView1"
runat="server"
DataSourceID="DataSourceSubmissionList"
KeyFieldName="SubmissionId"
</dx:ASPxGridView>
<asp:ObjectDataSource
ID="DataSourceSubmissionList"
runat="server"
TypeName="Project.WebUserControls.myapplications.sublayout">
</asp:ObjectDataSource>
/layouts/Portal/Company/Application/code.ascx.cs:
namespace Project.WebUserControls.myapplications
{
public partial class sublayout: System.Web.UI.UserControl
{
}
}
當我在code.ascx檔案中使用此行來獲取完全限定的型別名時...
<% Response.Write(typeof(Project.WebUserControls.myapplications.sublayout).AssemblyQualifiedName); %>
它將列印在頁面上。
Project.WebUserControls.myapplications.sublayout, App_Web_oiftguk4,
Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
但是,在ObjectDataSource TypeName中使用此確切型別(Project.WebUserControls.myapplications.sublayout)會導致錯誤。
關於此錯誤訊息,我經歷了很多問題。我已經讀過,可能的解決方案可能是在TypeName屬性like this中同時使用 namespace 和程式集名稱。但是我不能這樣做,因為程式碼是動態編譯的並且程式集名稱不斷變化。
另一件事-僅當使用CodeFile方法時才會發生此錯誤。如果我切換到CodBehind,沒問題。
發生這種現象的原因可能是什麼?
解決辦法
我通過在Page_Init期間初始化TypeName屬性而不是直接在ObjectDataSource中指定TypeName來解決了這個問題:
/layouts/Portal/Company/Application/code.ascx.cs:
public void Page_Init(object o, EventArgs e)
{
DataSourceSubmissionList.TypeName = this.GetType().AssemblyQualifiedName;
}
/layouts/Portal/Company/Application/code.ascx:
<asp:ObjectDataSource
ID="DataSourceSubmissionList"
runat="server"
</asp:ObjectDataSource>