如何从ASP.NET中的MasterPage调用内容方法

时间:2015-05-13 21:50:36

标签: c# asp.net webforms

我想从主页面调用内容的方法,发送参数来操作一个标签。

public partial class MasterCategoria : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSalada_Click(object sender, ImageClickEventArgs e)
    {
        produtosCategoria x = new produtosCategoria();
        x.changeLabel("Salada");
    }
}

在此WebForm上操作此按钮,这是一个内容

public partial class produtosCategoria : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void changeLabel(string name)
    {
        lblTexto.Text = name;
    }

但这不起作用。我该怎么做才能做到这一点?

谢谢你们,对我的英语感到抱歉。

1 个答案:

答案 0 :(得分:1)

已创建produtosCategoria类型的对象,可以通过this.Page从您的母版页访问该对象。

因此,您可以更改内容页面的标签,如下面的代码段所示。

另外,我添加了一个简单的类型检查,因此如果加载了另一个内容页面,您将不会收到错误

protected void btnSalada_Click(object sender, ImageClickEventArgs e)
{
    // Check if it is the correct content page
    if (this.Page.GetType() == typeof(produtosCategoria)) 
    {
        produtosCategoria x = (produtosCategoria)this.Page;
        x.changeLabel("Salada");
    }
}

注意:在母版页中执行代码this是母版页,this.Page是内容页