检查request.form["field"]字符串长度在ASP.net中不工作

本文关键字:quot ASP net 工作 form request field 字符串 检查 | 更新日期: 2023-09-27 17:50:14

我目前正在尝试验证我的ASP。净的形式。我需要确保用户输入了至少5个字符的密码。

我已经做了一个检查,以确保使用以下代码的内容是有效的:

else if (Request.Form["txtPassword"] == "")
{}

然后使用以下代码检查字符是否不小于5:

if (Request.Form["txtPassword"].Length < 5)
{}

然而,当我运行表单并提交它时,它没有向用户显示关于密码长度的错误,而是不断从Visual Studio获得错误。在我尝试提交表单之前,它显示:

对象引用未设置为对象的实例。

此错误仅在检查长度时显示,而不是在检查字符串为空时显示。

感谢您提供的帮助

检查request.form["field"]字符串长度在ASP.net中不工作

您有一个空引用异常。请求。Form["txtPassword"]返回null。这就是正在发生的事情:

string myString = null;
// This is valid comparison because myString is a string object.
// However, the string is not *empty*, it is null, thus it has *no* value.
if(myString == "")
{
    DoSomething();
}
// This is not acceptable, as null.Length has no meaning whatsoever.
// The expression compiles because the variable is of type string,
// However, the string is null, so the "Length" property cannot be called.
if(myString.Length < 5)
{
    DoSomethingElse();
}

不能访问空字符串的长度。试着用这个代替:

var myString = Request.Form["txtPassword"];
if(!String.IsNullOrEmpty(myString) && myString.Length < 5)
{
    DoSomething();
}
然而,下一个问题是,为什么它是空的?也许您不正确地将关联的表单输入命名为"txtPassword"以外的其他内容,或者可能数据没有通过POST发送。

这可能意味着Request.Form["txtPassword"]为空。我将首先检查它是否存在

你会收到这个错误,因为你在一个空对象上调用Length属性,在这个例子中是Request。表单["txtPassword"]为空,Length无法调用。

你可能想要确保你的文本框有ID "txtPassword"记住,asp.net之前的。net 4生成客户端ID像"ctl00_txtPassword",这成为表单字段,你可能需要输入Request.Form["ctl00_txtPassword"]。

我也遇到过类似的问题。我试图从一个项目发布到另一个项目。由于要求,我只能使用常规的HTML表单。这些值总是空的。这个问题让我绞尽脑汁,直到我偶然发现了解决办法。

第一个:在你的表单头没有runat="server"标签

 bad:  <form id="form1" runat="server"  action="http://yoursite.com/yourpage.aspx" method="post" >
 good: <form id="form1"   action="http://yoursite.com/yourpage.aspx" method="post" >
二:

。Net的html输入框为.Net HTML标签:<input id="myinput" type="text" />

结束标记/>是问题所在。如果你把/去掉,它就可以工作了。

 bad: <input id="myinput" type="text" />
 good: <input name="myinput" type="text" >

第三:一定要使用"name"属性而不是"id"属性

 bad: <input id="myinput" type="text" />
 good: <input name="myinput" type="text" >

如果表单标签放置在母版页中,例如:Site。,并且您提交的表单包含字段

& lt;asp:TextBox ID="amount" name="amount" runat="server"/>

,它实际上是在ContentPlaceHolder (ID="MainContent")中,然后如果你使用Request。形式["amount"]它不工作,总是显示空值在它…因为,当页面呈现时,id实际上变成了"ctl00$MainContent$amount"。因此,请求。表单["ctl00$MainContent$amount"]可以工作。