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");
}
%>
First, let me answer your question:
The first page load is a GET, postbacks are a POST (hence the name postback).
Request.Formis populated only if the page is loaded though a form POST.On the first page load,
Request.Formis an empty collection. SinceRequest.Formis aNameValueCollection, accessing a non-existent entry returns null. Thus,Request.Form["whatever"]returnsnullon the first page load.After a postback,
Request.Formis filled with values. Since HTTP POST does not know aboutnullvalues,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.Formyourself:Since TextBox.Text defaults to
"", there’s no need to check fornullhere.