Request.Form ["name"]什么时候为空,什么时候为空字符串? [英] When is Request.Form["name"] null and when an empty string?
问题描述
为什么即使文本框为空并且即使在回发中也没有被触摸,以下结果仍会导致true子句出现?:
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?
为什么以下结果在第一页加载时导致true if子句,而在回发时却没有true?:
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");
}
%>
推荐答案
首先,让我回答您的问题:
首页加载是GET,回发是POST(因此名为 post back).如果页面是通过POST表单加载的,则 Request.Form
仅填充 .
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.
-
在首页加载时,
Request.Form
是一个空集合.由于Request.Form
是NameValueCollection
,因此在首页加载时返回null
.
On the first page load,
Request.Form
is an empty collection. SinceRequest.Form
is aNameValueCollection
, accessing a non-existent entry returns null. Thus,Request.Form["whatever"]
returnsnull
on the first page load.
回发后, Request.Form
会填充值.由于HTTP POST不了解 null
的值,因此 Request.Form ["whatever"]
会为存在但为空的字段返回空字符串.
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.
如果要避免 x!= null&&x!="
模式,请使用 String.IsNullOrEmpty或空合并运算符:(x??")!="
.
If you want to avoid the x != null && x != ""
pattern, use String.IsNullOrEmpty or the null coalescing operator: (x ?? "") != ""
.
另一方面,您可以通过仅使用内置的WebForms功能来简化生活,而不用自己解析 Request.Form
:
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<%
}
%>
自 TextBox.Text 默认为"
,这里不需要检查 null
.
Since TextBox.Text defaults to ""
, there's no need to check for null
here.
这篇关于Request.Form ["name"]什么时候为空,什么时候为空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!