2016-05-04 34 views
0

我使用反射從頁面調用masterpage公共方法,但是一旦方法被調用,母版頁上的控件返回null ...爲什麼是這樣?C#反射:asp.net控件在母版頁上爲空

代碼在母版的文件:

public void Add_PageTitle(string title, string titleIcon = null, string titleSmallText = null, string title2 = null) 
{ 

    if (!string.IsNullOrEmpty(titleIcon)) 
     this.litPageTitleIcon.Text = "<i class=\"" + titleIcon + " position-left\"></i>"; 

    if (!string.IsNullOrEmpty(title)) 
     this.litPageTitleText.Text = " <span class=\"text-semibold\">" + title + "</span>" + (!string.IsNullOrEmpty(title2) ? " - " + title2 : ""); 

    if (!string.IsNullOrEmpty(titleSmallText)) 
     this.litPageTitleSmallText.Text = " <small class=\"display-block\">" + titleSmallText + "</small> "; 
} 

代碼在頁面文件:

Type masterType = this.Page.Master.GetType(); 
object classInstance = Activator.CreateInstance(masterType, null); 
MethodInfo miAddPageTitle = classInstance.GetType().GetMethod("Add_PageTitle", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); 
MethodInfo miHeadingElements = classInstance.GetType().GetMethod("Add_Heading_Elements", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); 

if (this.WorkingServiceRequest != null) 
    miAddPageTitle.Invoke(classInstance, new object[] { this.WorkingServiceRequest.QuestionPack.QuestionPackName, ((this.WorkingServiceRequest.ServiceType != null) ? this.WorkingServiceRequest.ServiceType.IconClass : string.Empty), ((this.WorkingServiceRequest.ServiceType != null) ? this.WorkingServiceRequest.ServiceType.Description : this.WorkingServiceRequest.QuestionPack.QuestionPackName), this.WorkingServiceRequest.Name }); 
else 
    miAddPageTitle.Invoke(classInstance, new object[] { questionPack.Name, questionPack.IconClass, questionPack.Description, string.Empty }); 

我可以調用在母版精細的方法,但對照 例如

<asp:Literal ID="litPageTitleIcon" runat="server"></asp:Literal> 
<asp:Literal ID="litPageTitleText" runat="server"></asp:Literal> 
<asp:Literal ID="litPageTitleSmallText" runat="server"></asp:Literal> 
在母版

「litPageTitleIcon,litPageTitleText」 返回null,這導致異常ofcause。

我在做什麼錯?

回答

0

那麼你正在用create實例創建一個新的母版頁,這就是爲什麼沒有可用的控件。

嘗試

var x = (MyMasterPageType)this.Page.Master; 
x.Add_PageTitle(questionPack.Name, questionPack.IconClass, questionPack.Description, string.Empty) 
+0

好吧,我就是用這個方法,你只是以實例闡述之前... 但我有這樣4個不同的masterpages ...所以我想我在做一個更好的辦法來擺脫如果... else語句... 由於...主頁有相同的方法 –

+0

創建一個接口,使主頁實現所述接口,將x轉換爲接口,或使用動態。 –

+0

然後它會在所述的masterpage中看到將實現接口的asp.net控件嗎? 我想擺脫這個 if (this.Page.Master is PageTemplate){ var master = (PageTemplate)this.Page.Master; } else if (this.Page.Master is PageTemplate_v2) { PageTemplate_v2 masterv2 = (PageTemplate_v2)this.Page.Master; }