从用户控件调用父页面上的方法
我正在使用我创建的用户控件(只是一个 .cs 文件而不是 .ascx 文件),它有一些魔力,并且根据控件生成的值,我需要它在“托管”的父页面上执行某些操作' 控制。在某些情况下需要调用一个方法(方法在父控件上)。
控件放置在父页面上,如下所示:
<customtag:MyControl ID="something" runat="server" />
我在控件本身上动态创建按钮等,但是当单击按钮时,例如,控件上有一个文本框,并且文本框的值是“ bob”,它需要调用包含控件的页面上的方法...我该如何完成此操作?
I am using a user control that I created (just a .cs file not an .ascx file), that does some magic and depending on a value generated by the control, I need it to do something on the parent page that is 'hosting' the control. It needs to call a method under certain circumstances (method is on the parent control).
the control is placed on the parent page like so:
<customtag:MyControl ID="something" runat="server" />
I'm dynamically creating buttons etc on the control itself but when a button is clicked, let's say for example that there's a text box on the control and if the value of the textbox is "bob" it needs to call a method on the page that's housing the control...how can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以按照casperOne的建议进行操作,但我不建议这样做。这将您的用户控件与父页面紧密耦合,这违背了用户控件的目的。
就我个人而言,我会向父页面可以处理的用户控件(例如
ButtonClicked
)添加一个事件。在父级的事件处理程序中,以您认为合适的方式处理该事件。通过这种方式,您可以稍后将用户控件插入到不同的页面,而不必担心用户控件中需要特定类型父页面的逻辑。You could do what casperOne suggested, but I wouldn't advise it. This is tightly coupling your user control to your parent page, which kind of defeats the purpose of a user control.
Personally, I'd add an event to the user control (say,
ButtonClicked
) that the parent page can handle. In the event handler in your parent, deal with the event however you see fit. This way you can plug the user control into a different page at a later date and not have to worry about logic in the user control that requires a specific kind of parent page.您应该能够通过 父属性。但是,它将作为控件返回给您。您必须将其转换为页面的类型才能访问您定义的页面上的任何方法。
You should be able to get the Page hosting the control through the Parent property. However, that's going to be returned to you as a Control. You have to cast it to the type of your page in order to access any methods on the page which you have defined.
我认为 casperOne 走在正确的轨道上,但还需要更进一步。我很高兴做出这样的假设:该用户控件将在更多页面上使用。 (我通常编写 VB.Net,抱歉,如果我的 C# 格式错误)
创建一个基本页面类(您可以将其存储在 App_Code 目录或项目中):
现在确保您的所有页面都从代码中的该页面继承后面的文件:
现在在您的用户控件中您知道页面类型是什么并且可以调用
I think that casperOne is on the right track, but you need to go a step further. I'm giong to make the assumption that this user control will be used on more then on page. (I normally write VB.Net, sorry if my C# is malformed)
Make a base page class (you can store it in your App_Code directory or in a project):
Now make sure that all of your pages inherit from this page in your code behind file:
Now in your user control you know what the page type is and can call