Removing specific QueryStrings
Let's assume an aspx page gets multiple querystrings, for 开发者_开发问答example books.aspx?author=Arthor&level=4&year=2004
.
I'd like to create a button that clears specific querystring.
For example when clearAuthorBtn
is clicked, user should be redirected to books.aspx?level=4&year=2004
How can I make it? Thank you very much.
ASP.NET, C# something like this pseudo-code should work in your button event handler:
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);
}
Here is a method that may help. I have not tested this particular implementation, but something like it should suffice (and be fairly robust).
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('&');
}
You can call the above method like this (note that I use HttpContext.Current in case you want to call this outside of an Page
or 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);
精彩评论