ASP.NET C# Error - Response is not available in this context.

Hi friends,

I have two files with the following codes...

test1.aspx.cs

public class test1 : System.Web.UI.Page
      {
            public void WriteName()
            {
                  Response.Write("Jazon");
            }

            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Put user code to initialize the page here
            }
                }




test2.aspx.cs

public class test2 : System.Web.UI.Page
      {
            private void Page_Load(object sender, System.EventArgs e)
            {
                  test1 t = new test1();
                  t.WriteName();
            }
      }


When I run this app, I get the "Response is not available in this context" error.

Any ideas on how to get around this?  I would like to be able to use Response.Write in the WriteName() subroutine.  I have a whole bunch of ASP code that have subroutines with Response.Write.  I just want to know how to convert these into good .NET code.

Thanks a bundle,


Jazon from Jacksonville, FL
LVL 3
piratepatrolAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

techjoshCommented:
Here is an explaination of the cause of your error... it gets kinda technical but hopefully you will find the information usefull.  The System.Web.UI.Page object has a read only member called Context which is of type HttpContext.  It also has a Response, Request, Server, and Session objects of types HttpResponse, HttpRequest, HttpServerUtility, and HttpSessionState respectively.  Unfortunately, all of those objects are all pointing to the same objects in the Context... so Page.Request is really pointing to Page.Context.Request, Page.Response points to Page.Context.Response, etc...  When the webserver creates an instance of test2 it gives it the current context.  When you create an instance of test1 from test2 it has no context therefor you cannot use the Request, Response, Server, or Session objects... To have page2 execute page1, you should do the following:

public class test1 : System.Web.UI.Page
     {
          public void WriteName()
          {
               Response.Write("Jazon");
          }

          private void Page_Load(object sender, System.EventArgs e)
          {
               // Put user code to initialize the page here
               WriteName();
          }
     }

public class test2 : System.Web.UI.Page
     {
          private void Page_Load(object sender, System.EventArgs e)
          {
               // create new instance of test1
               test1 t = new test1();
               // pass it the current context and start it rendering
               t.ProcessRequest(this.Context);
          }
     }

(disclaimer: I haven't actually tried the code above... just working from memory.  It may not work at all)

Alternatively, you could rewrite the WriteName method to refer to the current HttpContext like this:

public void WriteName()
{
    HttpContext.Current.Response.Write("Jason");
}

... but that gets to be pretty long-winded, especially if you use Response.Write often.  You could also override the Context object on Page1 to point to the current HttpContext:

protected override System.Web.HttpContext Context
{
    get
    {
        return System.Web.HttpContext.Current;
    }
}

This allows you to reference the Response, Request, Server, and Session objects normally because instead of pointing to the non-existant HttpContext object, they would now point to the current HttpContext object.

However, all of these methods are very messy and should only be used if no better way can be found to do what you need to do.  From the look of your example it looks like you're trying to port code from an ASP include file.  If you are looking for a way to port old code which, for instance, draws a dynamic menubar across multiple pages you should look into making that menubar its own WebControl.  Then you can drag and drop it onto multiple pages using the Visual Studio .NET IDE.  If you have more generic methods I'd recommend that you put them into a class libarary and refer to them from your pages instead of including additional pages while processing requests.

Also, remember that ASP.NET is object oriented... if you have a unified look across multiple pages, you might consider creating a template page and overriding the Render() method to produce the default page and then inheriting additional pages from that page... like this:

public class TemplatePage : System.Web.UI.Page
{
    public bool Restricted = False;
    public bool IsLoggedIn
    {
        get
        {
            return (Session["UserID"] == null) ? false : true;
        }
    }
    public override void Render(HtmlTextWriter w)
    {
        w.WriteLine("<!DOCTYPE....");
        w.WriteLine("<html><body>");

        if (Restricted && !IsLoggedIn)
        {
            Controls.Clear();
            Controls.Add(new LoginControl());
        }

        foreach (Control c in Controls)
        {
            c.Render(w);
        }

        w.WriteLine("</body></html>");
    }
}

public class WelcomePage : TemplatePage
{
    private void Page_Load(object sender, System.EventArgs e)
    {
        if (IsLoggedIn)
        {
            Controls.Add(new LiteralControl("Welcome Back " + Session["UserID"].ToString()));
        }
        else
        {
            Controls.Add(new LiteralControl("Please Login"));
        }
    }
}

public class MemberPage : TemplatePage
{
    public MemberPage()
    {
        Restricted = true;
        Controls.Add(new LiteralControl("Welcome to the members only area"));
    }
}


Theres a lot more to it than all that... the code above probably doesn't even compile.  Just an example... and one thats gone on far longer than I inteded to.  My apologies if this information isn't useful to you.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.