C# 母版页中的调用方法
我在asp.net母版页中有一个公共方法。是否可以从内容页调用此函数,如果可以,步骤/语法是什么?从C# 母版页中的调用方法,c#,.net,asp.net,master-pages,C#,.net,Asp.net,Master Pages,我在asp.net母版页中有一个公共方法。是否可以从内容页调用此函数,如果可以,步骤/语法是什么?从页面中可以将母版页面强制转换为特定类型(您自己的母版的类型,它公开了所需的功能),使用作为跳过任何类型不匹配的异常: MyMasterPageType master = (MyMasterPageType)this.Master; master.MasterPageMethod(); var master = Master as MyMasterPage; if (master != null)
页面中可以将母版页面强制转换为特定类型(您自己的母版的类型,它公开了所需的功能),使用作为跳过任何类型不匹配的异常:
MyMasterPageType master = (MyMasterPageType)this.Master;
master.MasterPageMethod();
var master = Master as MyMasterPage;
if (master != null)
{
master.Method();
}
在上述代码中,如果Master
不是MyMasterPage
类型,则Master
将为null
,并且不会尝试方法调用;否则它将按预期调用。您只需执行以下操作即可
MasterPageClassName MasterPage = (MasterPageClassName)Page.Master;
MasterPage.MasterMethod();
检查详细信息使用类似的工具,例如:
<%@ MasterType VirtualPath="~/masters/SourcePage.master" %>
可以将此作为静态成员添加到页面顶部吗?可以将此作为静态成员添加到页面顶部吗?不是静态成员,因为母版页特定于当前处理请求的页面。您可以为母版页创建一个实例属性:private MyMasterPageType master{get{return(MyMasterPageType)this.master;}}
首先查看Uwe Keim的答案;我发现它使用起来很简单。
Master.Method();