访问.ascx中的公共函数

时间:2011-03-09 23:17:53

标签: asp.net

如何使用C#访问.ascx文件中的公共函数? 感谢

4 个答案:

答案 0 :(得分:2)

如果函数不是静态的,则需要首先获取包含该函数的类的实例,然后在该实例上调用该函数。例如:

<%
    // obtain an instance of the type containing the function
    Foo instance = new Foo();
    // invoke the function on this instance
    string result = instance.Bar();
%>

显然,在代码隐藏文件中执行此操作会更好,而不是污染您的标记。

答案 1 :(得分:2)

与.NET Framework中的其他公共函数一样 - 通过对象引用。但有时Visual Studio不会自动查看您的用户控件的公共成员。如果IntelliSense窗口没有显示给您,请尝试重建用户控件和站点。

答案 2 :(得分:1)

你从哪里调用这个函数?包含页面?母版?家长控制?控制本身?无论如何,您需要以某种方式获取对控件实例的引用(除非该方法是静态的)才能调用此方法。并且引用的类型必须与定义方法的类的类型相匹配。

编辑:

MyControl myControl = (MyControl)Page.FindControl("Id_Of_The_Control"); 
if (myControl != null) 
{ 
    myControl.TheMethod(); 
}

答案 3 :(得分:1)

如果您不想以编程方式将ascx控件添加到占位符中,只需将IAttributeAccessorIUserControlDesignerAccessor接口实现到您的用户控件类,例如;

public partial class yourascxclassname: System.Web.UI.UserControl, IAttributeAccessor,  IUserControlDesignerAccessor

您只能访问ascx控件的公共成员。