简体   繁体   中英

How to send parameter to a function in Master.cs from a content page

In Master.cs :

public string sortOrder
{
    get
    {
        if (ViewState["sortOrder"].ToString() == "Desc")
        {
            ViewState["sortOrder"] = "Asc";
        }
        else
        {
            ViewState["sortOrder"] = "Desc";
        }

        return ViewState["sortOrder"].ToString();
    }
    set
    {
        ViewState["sortOrder"] = value;
    }
}

I am calling it from a content page:

ViewState["sortOrder"] = "Asc";
PD (e.SortExpression, Master.sortOrder, false);

When executing the function, I get the following error in this line

if (ViewState["sortOrder"].ToString() == "Desc"): Object reference not set to an instance of an object.

The sortOrder function worked fine when it was also in the content page. I am trying to move all my re-usable code to Master.cs file.

How can I modify the function so it works as it was in the content page.

The ViewState of the master and the content pages are not the same. On your content page, you are only modifying the ViewState of the content page, so your master page is getting the null reference as a result.

To persist data between the master and content pages, you have a few options:

  • If the data needs to persist across postbacks, then either use Session or reference the ViewState of the master through ((MasterType)Page.Master).sortOrder on Content code behinds
  • Otherwise, you can use the Context.Items object.

try to use this one.

public string sortOrder
{
      get
      {
           if (!string.IsNullOrEmpty(Convert.ToString(ViewState["sortOrder"])) && Convert.ToString(ViewState["sortOrder"]) == "Desc")
           {
                ViewState["sortOrder"] = "Asc";
           }
           else
           {
                ViewState["sortOrder"] = "Desc";
           }

           return Convert.ToString(ViewState["sortOrder"]);
      }
      set
      {
           ViewState["sortOrder"] = value;
      }
}

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