我有一个包含搜索表单的ASP.NET页面。
是否有任何解决方案,可以将搜索文本放在URL中?
我想要给我的客户提供复制/粘贴搜索结果URL的可能性。
可能有更好/更干净/更合适的方法来实现,例如更改 表单的操作 或更改按钮的 PostBackUrl,但这是我会做的。
.aspx:
<asp:Label ID="Label1" runat="server" Text="Search Term: "></asp:Label>
<asp:TextBox ID="txtSearchTerm" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search"
onclick="btnSearch_Click" />
.cs:
:protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
if (!string.IsNullOrEmpty(Request.QueryString["SearchTerm"]))
{
string searchTerm = Request.QueryString["SearchTerm"];
txtSearchTerm.Text = searchTerm;
DoSearch(searchTerm);
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtSearchTerm.Text.Trim()))
{
Response.Redirect("~/Search.aspx?SearchTerm=" + txtSearchTerm.Text.Trim());
}
}
private void DoSearch(string searchTerm)
{
//search logic here
Response.Write("Search result: " + searchTerm);
}
你也可以使用jQuery来完成这个技巧,像这样:
$(function(){
$('input[type="submit"]').click(function(e){
e.preventDefault();
var searchResult = "Search.aspx?q=" + $('input#textbox').val();
$('form#myForm').attr('action',searchResult);
});
});
<form id="myForm" action="Search.aspx" onsubmit="return setAction();">
<input id="textbox" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function setAction()
{
var myForm = document.getElementById( "myForm" );
var myText = document.getElementById( "textbox" );
if (myForm && myForm.action && myText && myText.value != null )
{
myForm.action = "Search.aspx?q=" + myText.value;
}
return true;
}
</script>
个人而言,我不是 JavaScript 的铁粉... 但这并不会对服务器造成额外的请求。如果您认为这有任何缺点,请告诉我。