ASP:RUNAT =服务器进行动态控制 [英] ASP: runat=server for dynamic control
问题描述
在Page_Load方法创建一些控件,根据各种条件。我想与这些控件注册服务器端code。然而,在过去的一部分,我需要声明我的控件服务器控件。这通常是由RUNAT =服务器完成的,但我不知道如何设置在C#code此属性。 myControl.Attributes.Add(RUNAT,服务器)不会做的伎俩。这一件作品,这意味着,当我点击它的测试方法被调用:
In the Page_Load method I create a couple of controls, based on various conditions. I would like to register server side code with those controls. However, for the last part I need to declare my controls as server controls. This is normally done by runat=server, but I don't know how to set this attribute in the C# code. myControl.Attributes.Add("runat", "server") does not do the trick. This one works, meaning that the "test" method is called when I click on it:
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="test">testtext</asp:LinkButton>
这一个不工作:
LinkButton lb = new LinkButton();
lb.ID = "LinkButton1";
lb.OnClientClick = "test";
lb.Text = "testtext";
lb.Attributes.Add("runat", "server");
我可以点击它,并在页面加载,但试验方法不被调用。
I can click on it, and the page is loaded, but the test-method is not called.
任何提示?
推荐答案
您几乎得到了它的权利。只是一对夫妇的事情:
You almost got it right. Just a couple things:
- 当你手动实例化服务器控件,没有必要添加
=服务器
属性。这是唯一使用的ASP.NET页面分析程序从其他标记区分服务器控件一个特殊的属性。 - 标记中的
的OnClick
属性对应于点击
服务器端事件,您挂钩使用+ =
运营商。 (另外,在标记中的的OnClientClick
属性对应于的onclick
的客户端属性,它通常包含的JavaScript code片段。事实上,的OnClick
不符合的onclick
是不可否认有点混乱。)
- When you manually instantiate a server control, there's no need to add the
runat="server"
attribute. This is a special attribute that's used only by the ASP.NET page parser to distinguish server controls from other markup. - The
OnClick
attribute in markup corresponds to theClick
server-side event, which you hook up using the+=
operator. (On the other hand, theOnClientClick
attribute in markup corresponds to theonclick
client-side attribute, which typically contains a snippet of JavaScript code. The fact thatOnClick
doesn't correspond toonclick
is admittedly a bit confusing.)
因此:
LinkButton lb = new LinkButton();
lb.ID = "LinkButton1";
lb.Click += test;
lb.Text = "testtext";
和事件处理函数(你甚至可以使私人
如果有,将其从标记的引用):
And your event handler (which you can even make private
if there are no references to it from markup):
protected void test(object sender, EventArgs e)
{
}
这篇关于ASP:RUNAT =服务器进行动态控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!