简体   繁体   中英

MasterPage Access Controls

I have 2 master page in my web site.

  1. MainMaster
  2. SubMaster (Master Page:MainMaster)
  3. Page (Master Page:SubMaster)

I have hidden fields on SubMasterPage. And i'm proccessing datas and setting hidden field value on SubMasterPage Init event. I want to get hiddenfield's value from Page.aspx I'm trying this on Page.aspx, getting "Object reference not set to an instance of an object." error

 ((HiddenField)this.Master.FindControl("hiddenId")).Value

But when i have 1 master page this code works normally.

Have ia solution in this problem? Or should i try transfer datas via session/querystring etc?

You could add a property to your sub master page to return the value, and use this in the child page.

eg.

Sub Master Page

public string HiddenValue
{
   get
   {
      //return the value of your hidden field
      return HiddenID.Value;
   }
}

Child page:

//Method to get the hidden value from the master page, if the master page is a sub master page
private string GetHiddenValue()
{
   if (this.Master is SubMasterPage)
   {
      string value = (this.Master as SubMasterPage).HiddenValue;
      return value;
   }
   else
   {
      return string.Empty;
   }
}

if you want to go one step further you could add an extension method to the MasterPage class to call it easily from any page.

eg:

public static class MasterPageExtensions
{
    public static string GetHiddenFieldValue(this MasterPage master)
    {
        if (master is SubMasterPage)
            return (master as SubMasterPage).HiddenFieldValue;
        else
            return string.Empty;
    }
}

public class SubMasterPage : MasterPage
{
    private HiddenField _hiddenField;

    public string HiddenFieldValue
    {
        get
        {
            return _hiddenField.Value;
        }
    }
}

public class ChildPage : Page
{
    void TestMethod()
    {
        string hiddenValue = this.Master.GetHiddenFieldValue();
    }
}

this is particularly useful when for example you have a single modal popup message box on the master page, and you want to show it from any child page.

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