Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is Request.Form["name"] null and when an empty string?

Why do the following result in a true if clause even though the textbox is empty and not even touched on a postback? :

<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>

<%
if (Request.Form["name"] != null) // Prints out "Name OK" on postback.
{
    Response.Write("<br/>");
    Response.Write("Name OK");
}
%>

Does the textbox actually contain an empty string ("") on a postback?


Why do the following result in a true if clause on the first page load but not on a postback? :

<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>

<%
if (Request.Form["name"] != "") // Prints out "Name OK" on first page load, but not on postback.
{
    Response.Write("<br/>");
    Response.Write("Name OK");
}
%>

To get a successful and expected result I have to use the following:

<form action="Default.aspx" runat="server" method="post" id="newform">
<input type="text" id="name" runat="server"/>
</form>

<%
if (Request.Form["name"] != null && Request.Form["name"] != "")
{
    Response.Write("<br/>");
    Response.Write("Name OK");
}
%>
like image 932
Birdman Avatar asked Jan 03 '12 12:01

Birdman


1 Answers

First, let me answer your question:

The first page load is a GET, postbacks are a POST (hence the name postback). Request.Form is populated only if the page is loaded though a form POST.

  • On the first page load, Request.Form is an empty collection. Since Request.Form is a NameValueCollection, accessing a non-existent entry returns null. Thus, Request.Form["whatever"] returns null on the first page load.

  • After a postback, Request.Form is filled with values. Since HTTP POST does not know about null values, Request.Form["whatever"] returns an empty string for fields which are present but empty.

If you want to avoid the x != null && x != "" pattern, use String.IsNullOrEmpty or the null coalescing operator: (x ?? "") != "".


On the other hand, you could make your life a lot easier by just using the built-in WebForms features instead of parsing Request.Form yourself:

<form runat="server">
    <asp:TextBox ID="nameBox" runat="server" />
    <asp:Button Text="Do Postback" runat="server" />
</form>

<%
    if (nameBox.Text != "")
    {
        %><br />Name OK<%
    }
%>

Since TextBox.Text defaults to "", there's no need to check for null here.

like image 122
Heinzi Avatar answered Oct 02 '22 06:10

Heinzi