无法修改Controls集合,因为该控件包含代码块(即<%…%>)动态添加具有母版页的控件
本文关键字:控件 动态 母版页 添加 集合 Controls 修改 因为 代码 包含 | 更新日期: 2023-09-27 18:06:13
不能修改控件集合,因为当动态添加具有母版页的控件时,控件包含代码块(即<%…%>)
我正在尝试添加一个隐藏字段控件到aspx页面。我得到下面提到的错误
无法修改Controls集合,因为该控件包含代码块(即<%…%>)。
当我必须动态添加控件时,就会发生这种情况。在网上,我找到了所有类型的答案,用<%#代替<%=。在我的情况下,这根本不适用。
这是我的代码示例, HiddenField hndGuid = new HiddenField();
_page.Form.Controls.Add(hndGuid);
指针吗?
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
namespace wwwroot.Common
{
public class GuidClass
{
public GuidClass()
{
//
// TODO: Add constructor logic here
//
}
private string guid;
public string Guid
{
get
{
return guid;
}
set
{
guid = value;
}
}
}
public class Myhandler : System.Web.UI.Page, IHttpModule
{
Page _page = null;
HiddenField hndGuid = null;
Queue<string> temp;
public Myhandler()
{
temp=new Queue<string>();
}
public new void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
System.Web.HttpContext _httpContext = System.Web.HttpContext.Current;
if (_httpContext != null)
{
_page = _httpContext.Handler as System.Web.UI.Page;
if (_page != null)
{
_page.Init += new EventHandler(_page_Init);
_page.Load += new EventHandler(_page_Load);
hndGuid = new HiddenField();
hndGuid.ID = "hndGuid";
}
else
{
return;
}
}
else
{
return;
}
}
void _page_Init(object sender, EventArgs e)
{
_page.Form.Controls.Add(hndGuid);
if (!_page.IsPostBack)
hndGuid.Value = Guid.NewGuid().ToString();
}
void _page_Load(object sender, EventArgs e)
{
GuidClass currentGuid =new GuidClass();
currentGuid.Guid = hndGuid.Value;
System.Web.HttpContext _httpContext = System.Web.HttpContext.Current;
if (temp.Contains<string>(currentGuid.Guid))
{
_httpContext.Items.Add("IsRefresh",true);
}
else
{
if(!(currentGuid.Guid.Equals(null)||currentGuid.Guid.Equals("")))
temp.Enqueue(currentGuid.Guid);
_httpContext.Items.Add("IsRefresh",false);
}
}
}
}
将代码块移动到单独的用户控件中,不需要后面的代码
http://csharpin.blogspot.com/2011/05/about-the-controls-collection-cannot-be.html