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

Why is the following result true if, although the text field is empty and does not even affect the 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 text field really contain an empty string ("") for postback?


Why does the following result appear in the true if clause on the first page, but not in the 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");
}
%>
+5
source share
3 answers

First let me answer your question:

The first page load is GET, postbacks are POST (hence the name post ). Request.Formit is filled only if the page is loaded using the POST form.

  • Request.Form . Request.Form NameValueCollection, null. , Request.Form["whatever"] null .

  • Request.Form . HTTP POST null, Request.Form["whatever"] , , .

x != null && x != "", String.IsNullOrEmpty : (x ?? "") != "".


, , WebForms , Request.Form:

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

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

TextBox.Text "", null.

+10

Request.Form NameValueCollection, null, key , ( ) .

string.IsNullOrEmpty().

if (!string.IsNullOrEmpty(Request.Form["name"]))
{
  Response.Write("<br/>");
  Response.Write("Name OK");
}
+2

Request.Form["ControlName"] null, .

, null , Request.Form["ControlName"] String.Empty.

, , (Request.Form["ControlName"] != null) (!String.IsNullOrEmpty(Request.Form["ControlName"]))

+2

All Articles