[英]Accessing masterpage code behind code from a child pages .ASPX page
我希望在我的 Masterpage 后面的代碼中執行代碼,並在像Default.aspx
這樣的子頁面的 .aspx 頁面上使用它,而不必通過Default.aspx.cs
頁面調用它。
這是我通過像這樣訪問它的嘗試<% MasterPage.getPlanCost() %>
,但是,這不起作用。 因為getPlanCost()
沒有“定義”
后面的母版頁代碼:
public string getPlanCost()
{
var country = getCountry();
string gbp = "£5.99";
string euro = "€6.99";
string usd = "$8.99";
var currencyCost = usd;
if (country == "United Kingdom") // gbp
{
currencyCost = gbp;
}
else if (country == "United States" || country == "Canada" || country == "Australia" || country == "New Zealand") // usd
{
currencyCost = usd;
}
else // euro
{
currencyCost = euro;
}
return currencyCost;
}
默認.aspx 頁面:
<p class="text-center under-title text-muted"><%=MasterPage.getPlanCost() %> Cancel Anytime.</p>
實現這一目標的最快/最有效的方法是什么? 此外,我嘗試使用在 StackOverflow 上看到的替代方法,使用get
和set
但是我無法讓它工作。 對 C# 相當陌生,所以我很抱歉。
盡管您已經找到了一種解決方法,但可以從子 Web 表單訪問母版頁方法,這在希望您的子頁面以某種方式影響母版頁的情況下非常有用。 您可以通過Page.Master
屬性執行此Page.Master
,但您首先必須注冊類型或Page.Master
類型。
方法一:注冊主類型
網頁表格:
<%@ Page Language="C#" MasterPageFile="~/Example.Master" ... %>
<%@ MasterType VirtualPath="~/Example.Master" %>
背后的代碼:
Page.Master.getPlanCost();
方法二:鑄造大師屬性
背后的代碼:
((Example)Page.Master).getPlanCost();
對於任何想知道的人,我創建了一個名為 Utilities.cs 的類
然后從我的 Default.aspx 頁面直接從這里調用它。
<%=Utilities.getPlanCost()%>
我還要感謝@Joel Coehoorn 的評論,這讓我走到了一半。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.