Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2004-11-03
1
Medium Priority
?
887 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:piratepatrol
1 Comment
 
LVL 3

Accepted Solution

by:
techjosh earned 600 total points
ID: 12490856
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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
CTAs encourage people to do something specific to show interest in your company, product or service. Keep reading to learn why CTAs should always be thought of as extremely important, albeit small, sections of websites.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.
Suggested Courses
Course of the Month11 days, 22 hours left to enroll

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question