ASP.NET:阅读形成搜索表单的动作页的变量值
题
我有一个网站,我想实现搜索functionality.So我加入了下面的代码有一个搜索框在我的html页面
<form id="search" method="post" action="Results.aspx">
<input id="txtSearchKey" type="text" name="txtSearchKey" />
<input id="Submit1" type="submit" value="submit" /><br />
<br />
</form>
在Results.aspx,我想读值用户在txtSearchKey文本框中进入。什么是理想的方式做到这一点?我用
string strKey = Request.Form["txtSearchKey"].ToString();
但它抛出一个空引用异常。请建议
我不想在ASP.NET.I所有页面希望有只有结果页面ASP.NET
在预先感谢
解决方案
可能是因为你没有一个命名属性的文本字段。这是被用作Request.Form集合中键的值。没有名称属性的输入字段将不被提交,我想。
例如为:
<input id="txtSearchKey" type="text" name="txtSearchKey" />
其他提示
您可以通过这个让你txtSearchKey领域:
string strKey = PreviousPage.Request.Form["txtSearchKey"].ToString();
但是,而不是使用表单动作转发搜索到另一个页面,你可以用一个按钮PostBackUrl属性这样的:
<asp:Button runat="server" ID="btnSearch" PostBackUrl="Search.aspx" />
由于在ASP.NET,能有多于一个的形式是不允许的。
是否有您不使用
任何理由形式RUNAT = “服务器”
和然后拖动一个TextField并以这种形式的按钮。然后双击你想要的按钮,写代码。
如果你想要做你的方式,你需要给你个名字=“txtMySearchKey”为它工作。
在处理事情的方式是不是真的在你的ASP.NET Web表单的工作方式。首选的方法是使用asp.net服务器控件和事件,以抽象的,你正在努力实现的过程。例如,你的表格应该真的是这样的(注意RUNAT =“server”属性,使您可以参考编程控件):
<form id="form1" runat="server">
<div>
<asp:Panel ID="PanelSearch" runat="server" DefaultButton="ButtonSubmit">
<asp:TextBox ID="TxtSearchKey" runat="server" /><br />
<asp:Button ID="ButtonSubmit" Text="Submit" runat="server"
onclick="ButtonSubmit_Click" /><br />
</asp:Panel>
</div>
</form>
然后,在后面的代码,你会处理这样的ButtonSubmit_Click
事件,使您能够获得来自TxtSearchKey
文本框中的值:
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
string strKey = TxtSearchKey.Text;
}
只是不要在REQUEST.FORM后使用的ToString()... ...之后,它不会给空引用。
不隶属于 StackOverflow