【问题标题】:Set master page file using function使用函数设置母版页文件
【发布时间】:2014-06-17 07:53:54
【问题描述】:

我想使用另一个类函数更改母版文件

例子:

public class XYZClass 
{
    public void CheckLogin(object ses,bool ipb,ref MasterPage page)
    {
        if (!(ses == null))
        {
            if (ses.ToString() == "Admin")
                page.MasterPageFile = "~/Admin.master";
            else
                page.MasterPageFile = "~/MasterPage.master";
        }
        else 
        {
            Response.Redirect("~/frmLogin.aspx");
        }
    }
}

public partial class frmDoctorHistory : System.Web.UI.Page
{
    BLLcheckLogin checkLogin = null;    
    protected void Page_PreInit(object sender, EventArgs e)
    {
        checkLogin = new BLLcheckLogin();
        checkLogin.CheckLogin(Session["usertype"], IsPostBack, ref MasterPageFile);
    }

}

我从另一个 aspx 源文件调用这个函数,它给了我一个错误,比如 “不能将属性、索引器或动态成员访问作为 out 或 ref 参数传递”。

【问题讨论】:

  • MasterPage 是一个对象,所以不需要通过引用传递。从您的方法声明和方法调用中删除“ref”以解决该错误。

标签: c# asp.net


【解决方案1】:

您可以在 PreInit 事件之前设置母版页。

请参阅MSDN 中的代码示例作为参考。

void Page_PreInit(Object sender, EventArgs e)
{
    this.MasterPageFile = "~/NewMaster.master";
}

您必须将当前代码重写为:

public void CheckLogin(object ses,bool ipb, Page page)
{
    if (!(ses == null))
    {
        if (ses.ToString() == "Admin")
            page.MasterPageFile = "~/Admin.master";
        else
            page.MasterPageFile = "~/MasterPage.master";
    }
    else 
    {
        Response.Redirect("~/frmLogin.aspx");
    }
}

protected void Page_PreInit(object sender, EventArgs e)
{
    checkLogin = new BLLcheckLogin();
    MasterPage mp;
    checkLogin.CheckLogin(Session["usertype"], IsPostBack, this);
}

我更改了您的代码以传递 Page 而不是 MasterPageFile 属性。那么 Ref 就不再需要了。

【讨论】:

  • 但我有一个类具有更改母版文件的功能。我从 aspx 源文件调用这个函数
  • 但是您不能在 PreInit 之后的事件中执行此操作。为时已晚。
  • 不,我有像业务逻辑这样的简单类。并且该类具有具有这些代码的功能。以及使用对象调用的函数
  • 但是从那个被调用的事件中呢?
  • 只有我想知道,我该怎么做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多