How to correctly create Page objects in asp.net behind code.

1.5k Views Asked by At

I am still fairy new to C# development and have a question about creating objects.

I am working on a website and I want to pull form values in the behind code after submit. Ultimately I am trying to convert a page to a user control.

Now I am trying to make an instance of a Page object (System.Web.UI.Page) so I can access the Request property of the object and read the submit values.

My problem is, it always throws a NullReferenceException and doesn't read the submitted values

Here is my code:

<form id="myForm" runat="server" > 
Name: <input type="text" name="name" id="name" /> 
<input type="submit" value="Submit Name" /> 
</form>


public partial class testing1 : BasePage
{
// Created an instance of Page Object
public System.Web.UI.Page requestVar;

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        // Try and use request, throws null exception
        string holder = requestVar.Request["name"];
    }
    catch (NullReferenceException)
    { }
}

}

Any idea why I get the null exception? What would be the correct way to create a Page object so I can use it's Request property?

Please let me know, Thank you!

2

There are 2 best solutions below

3
On BEST ANSWER

Use method="POST" in the form tag.

<form id="myForm" runat="server" method="POST" > 
    Name: <input type="text" name="name" id="name" /> 
          <input type="submit" value="Submit Name" /> 
</form>

and in code use Request.Form["name"]

try
{
    string holder = Request.Form["name"];
}
catch (Exception ex)
{ }
1
On

I am surprised that your code compiled. Normally the compiler can detect uninitialized variables. I'm guessing your example left some stuff out.

Anyway, to address your specific question, change

public System.Web.UI.Page requestVar;

to

public System.Web.UI.Page requestVar = new Page();

That being said, you don't need a Page object. If you need to access the request, you can obtain a reference to it using

var request = HttpContext.Current.Request;
var someVariable = request["ParamName"];