简体   繁体   中英

How to access variables declared in a different content place holder in a master page?

I want to setup a test in the head place holder to see that all that all the required information is present in order to load the page with no errors.

I would like to avoid doing this test on every place holder since I want to minimize data usage.

How can I access varibles declared in one content place holder from another

demo of problematic code:

<asp:Content ID="Content1" ContentPlaceHolderID="PHHead" Runat="Server">
    <%
    'Variable declaration
    dim something as integer = 1
    %>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="PHMain" Runat="Server">
   <%
   'this returns an error that the variable does not exist:
   response.write(something)
   %>
</asp:Content>

I was just bumping up against this same issue (for the umpteenth time) and ran across this old question, so...

My most likely answer is usually to either:

  • move the value creation into the code-behind or MVC controller (which can place it in ViewData) and let the code in each content section reference it from there.
  • have the first instance on the content page store the value in ViewData or in the HttpContext.Current.Items key-value collection from where successive references in other content sections can access it. (Eg, follow your dim something as integer = 1 with something like ViewData["something"] = something; or Context.Items["something"] = something; and access it similarly from elsewhere.) Similar to storing it in session or application, but specific to and expiring after the current request context.

Of course, whether either of these work for you that simply will depend on your own specific context.

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