动态加载用户控制
本文关键字:控制 用户 加载 动态 | 更新日期: 2023-09-27 18:10:28
我的代码如下
string[] keys = { "myCustomUserControl.ascx", "myCustomUserControl.ascx.cs", "myCustomUserControl.ascx.designer.cs" };
string customUserControlName = CommonDataCalls.GetCustomUserControlName(keys);
UserControl objUserControl = (UserControl)this.LoadControl("~/UserControls/" + userControlName);
userControlPlaceHolder.Controls.Add(objUserControl);
GetCustomUserControlName的定义如下
public string GetCustomUserControlName(string[] keys)
{
try
{
string userConrolsPhysicalPtah = System.Web.HttpContext.Current.Server.MapPath("~/UserControls/");
DataTable objDataTable = new DataTable();
foreach (string key in keys)
{
objRequestVO.addObject("ACA_KEY", key);
CResponseVO objResponseVO = (CResponseVO)objGateway.ExecuteBusinessService(CConstant.ADMIN, CConstant.ASSEMBLY_INFO, CConstant.SELECT, objRequestVO);
DataSet objDataSet = (DataSet)objResponseVO.getObject("RES_DS");
cUserTrce objGeneral = new cUserTrce();
if (!objGeneral.IsNullOrEmptyDataset(objDataSet))
{
if (objDataTable.Rows.Count == 0)
{
objDataTable = objDataSet.Tables[0].Clone();
}
objDataTable.Rows.Add(objDataSet.Tables[0].Rows[0].ItemArray);
}
}
if (objDataTable != null && objDataTable.Rows.Count == 3)
{
string containerName = "usercontrols";
foreach (DataRow dr in objDataTable.Rows)
{
string userControlFileBlobUrl = dr["ACA_ASSEMBLY_PATH"].ToString();
string userControlFileName = dr["ACA_CLASS_NAME"].ToString();
Storage.Blob blobHandler = new Storage.Blob();
Stream blobstream = blobHandler.GetBlob(userControlFileBlobUrl, containerName);
if (!(File.Exists(userConrolsPhysicalPtah + userControlFileName)))
{
MemoryStream ms = (MemoryStream)blobstream;
FileStream outStream = File.OpenWrite(userConrolsPhysicalPtah + userControlFileName);
ms.WriteTo(outStream);
outStream.Flush();
outStream.Close();
}
}
string customUserControlName = (from DataRow row in objDataTable.Rows
where row["ACA_KEY"].ToString() == keys[0]
select row["ACA_CLASS_NAME"].ToString()).First();
return customUserControlName;
}
else
{
return null;
}
}
catch
{
return null;
}
}
该方法基本上在运行时将用户控件复制到虚拟路径。
在aspx.cs页面我尝试动态加载它。
但是我可以看到文件被复制到虚拟路径,但是这个。加载控制给了我一个异常,说不能加载类型'myCustomUserControl'。
我正在使用azure web角色
我解决了这个bug。我放在这里只是供大家参考。
这是一个词的变化-
http://blog.kjeldby.dk/2008/11/dynamic-compilation-in-a-web-application/改变后台代码="myCustomUserControl.ascx.cs"CodeFile = " myCustomUserControl.ascx.cs "
感谢@Roopesh &@Kristoffer Brinch Kjeldby