Learn12 Learn12 - 11 days ago 5
ASP.NET (C#) Question

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

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!

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)
{ }