我们假设一个aspx页面有多个查询字符串,例如books.aspx?author=Arthor&level=4&year=2004
。
我想创建一个清除特定查询字符串的按钮。
例如,点击clearAuthorBtn
时,应将用户重定向到books.aspx?level=4&year=2004
我该怎么做? 非常感谢你。
答案 0 :(得分:3)
ASP.NET,C#这样的伪代码应该在你的按钮事件处理程序中起作用:
foreach (var key in Request.QueryString)
{
string url = "books.aspx?";
if (key != "author")
{
url = url + Server.UrlEncode(key) + "=" + Server.UrlEncode(Request.QueryString[key]) + "&";
}
Response.Redirect(url);
}
答案 1 :(得分:2)
这是一种可能有用的方法。我没有测试过这个特定的实现,但类似的东西应该足够了(并且相当健壮)。
public static string GetQueryStringWithoutKey(HttpRequest request, string keyToRemove) {
// Assert keyToRemove is not null.
if (keyToRemove == null) {
throw new ArgumentNullException("keyToRemove");
}
// If the QueryString has no data, simply return an empty string.
if (request.QueryString.AllKeys.Length == 0) {
return string.Empty;
}
// Reconstruct the QueryString with everything except the existing key/value pair.
StringBuilder queryStringWithoutKey = new StringBuilder();
for (int i = 0; i < request.QueryString.AllKeys.Length; i++) {
// Only append data that is not the given key/value pair.
if (request.QueryString.AllKeys[i] != null &&
request.QueryString.AllKeys[i].ToLower() != keyToRemove.ToLower()) {
queryStringWithoutKey.Append(request.QueryString.AllKeys[i]);
queryStringWithoutKey.Append("=");
queryStringWithoutKey.Append(request.QueryString[i]);
queryStringWithoutKey.Append("&");
}
}
// We might have had a key, but if the only key was Message, then there is no
// data to return for the QueryString.
if (queryStringWithoutKey.Length == 0) {
return string.Empty;
}
// Remove trailing ampersand.
return queryStringWithoutKey.ToString().TrimEnd('&');
}
你可以像这样调用上面的方法(注意我使用HttpContext.Current,以防你想在Page
或UserControl
之外调用它):
HttpRequest request = HttpContext.Current.Request;
string url = request.ServerVariables["PATH_INFO"];
string queryString = GetQueryStringWithoutKey(request, "author");
if (!string.IsNullOrEmpty(queryString) {
url += "?" + queryString;
}
HttpContext.Current.Response.Redirect(url);