Jer*_*son 39 c# asp.net user-controls webusercontrol
我在aspx页面中注册了一个用户控件在用户控件中单击按钮事件时,如何调用父页面代码隐藏中的方法?
谢谢.
Ste*_*edd 114
以下是使用Freddy Rios(来自Web应用程序项目的C#)建议的事件的经典示例.这假定您要使用现有委托而不是自己创建委托,并且您没有通过事件参数传递特定于父页面的任何内容.
在用户控件的代码隐藏中(如果不使用代码隐藏或C#,则根据需要进行调整):
public partial class MyUserControl : System.Web.UI.UserControl
{
public event EventHandler UserControlButtonClicked;
private void OnUserControlButtonClick()
{
if (UserControlButtonClicked != null)
{
UserControlButtonClicked(this, EventArgs.Empty);
}
}
protected void TheButton_Click(object sender, EventArgs e)
{
// .... do stuff then fire off the event
OnUserControlButtonClick();
}
// .... other code for the user control beyond this point
}
Run Code Online (Sandbox Code Playgroud)
在页面本身中,您使用以下内容订阅事件:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// hook up event handler for exposed user control event
MyUserControl.UserControlButtonClicked += new
EventHandler(MyUserControl_UserControlButtonClicked);
}
private void MyUserControl_UserControlButtonClicked(object sender, EventArgs e)
{
// ... do something when event is fired
}
}
Run Code Online (Sandbox Code Playgroud)
Rex*_*x M 14
将页面强制转换为项目中的特定页面:
((MyPageName)this.Page).CustomMethod()
Run Code Online (Sandbox Code Playgroud)
egl*_*ius 10
我建议您不要直接调用页面方法,因为您将控件绑定到特定页面.
而是公开一个事件,并让页面订阅它.它适用于任意数量的页面,当控件在单个页面上多次(甚至可能在列表中)时可以更容易地使用,并且更符合asp.control设计.
小智 5
遵循良好和适当的方法,
使用事件和委托概念使委托与父页面中的方法具有相同的签名,然后在父页面加载事件中为其分配父方法,然后通过用户控件中的事件调用此委托。
下面给出了代码示例和链接。
//Parent Page aspx.cs part
public partial class getproductdetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ucPrompt.checkIfExist += new uc_prompt.customHandler(MyParentMethod);
}
bool MyParentMethod(object sender)
{
//Do Work
}
}
//User control parts
public partial class uc_prompt : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public delegate bool customHandler(object sender);
public event customHandler checkIfExist;
protected void btnYes_Click(object sender, EventArgs e)
{
checkIfExist(sender);
}
}
Run Code Online (Sandbox Code Playgroud)
阅读更多详细信息它是如何工作的(参考):-
| 归档时间: |
|
| 查看次数: |
84273 次 |
| 最近记录: |