我有一个母版页,后面有以下代码
public partial class MasterPage : System.Web.UI.MasterPage
{
public SqlConnection cnx;
protected void Page_Load(object sender, EventArgs e)
{
}
}
如何从使用此母版页的 aspx.cs 文件中引用公共 SqlConnection cnx 属性?
我有一个母版页,后面有以下代码
public partial class MasterPage : System.Web.UI.MasterPage
{
public SqlConnection cnx;
protected void Page_Load(object sender, EventArgs e)
{
}
}
如何从使用此母版页的 aspx.cs 文件中引用公共 SqlConnection cnx 属性?
你有几个选择:
Master
属性转换为您的MasterPage
类型并从那里开始。 <%@ MasterType virtualpath="~/path/to/master.master" %>
在您的 aspx 文件中,该文件将强类型化 Master 属性。在您的母版页中:
public SqlConnection CnxInMasterPage
{
get { return this.cnx; }
}
在内容页面中(首先添加使用,以便您可以引用“MasterPage”类型)
var cnx = ((MasterPage)Master).CnxInMasterPage;
您应该声明一个接口IMyMasterPage
并将属性放在那里。允许您的母版页实现它。
然后,您可以在您的页面上执行此操作。
var myMasterPage = this.MasterPage as IMyMasterPage