Reputation: 786
I'm looking to execute code in my code behind on my Masterpage, and use it on the .aspx page of child pages like Default.aspx
, without having to call it through the Default.aspx.cs
page.
This is my attempt by accessing it like so <% MasterPage.getPlanCost() %>
, however, this does not work. As there's "no definition" for getPlanCost()
Master Page code behind:
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;
}
Default.aspx page:
<p class="text-center under-title text-muted"><%=MasterPage.getPlanCost() %> Cancel Anytime.</p>
What is the quickest / most efficient way of achieving this? Furthermore, I have tried to use alternate methods seen on StackOverflow, using get
and set
however I was unable to get this working. Fairly new to C# so I apologise.
Upvotes: 0
Views: 436
Reputation: 6304
Although you have found a workaround, it is possible to access master page methods from child web forms, useful in cases where want your child page to affect the master page in some way. You can do this through the Page.Master
property, but you will first have to register the type or cast it.
Method 1: Registering Master Type
Web Form:
<%@ Page Language="C#" MasterPageFile="~/Example.Master" ... %>
<%@ MasterType VirtualPath="~/Example.Master" %>
Code Behind:
Page.Master.getPlanCost();
Method 2: Casting Master Property
Code Behind:
((Example)Page.Master).getPlanCost();
Upvotes: 2
Reputation: 786
To anybody wondering, I created a class called Utilities.cs
Then called it directly from here from my Default.aspx page instead.
<%=Utilities.getPlanCost()%>
I'd also like to thank @Joel Coehoorn for his comments which got me halfway there.
Upvotes: 0