简体   繁体   中英

Accessing masterpage code behind code from a child pages .ASPX page

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.

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM