且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改单个URL查询字符串值

更新时间:2023-02-23 08:27:35

您不能修改QueryString直接,因为它是只读的。您将需要得到的值,修改它们,然后把他们重新走到一起。试试这个:

You can't modify the QueryString directly as it is readonly. You will need to get the values, modify them, then put them back together. Try this:

var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("page", "2");
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
Response.Redirect(url + updatedQueryString);

ParseQueryString 方法回报一NameValueCollection$c$c> (其实它真的返回 HttpValueCollection 其中EN codeS的结果,as我在回答另一个问题提)。然后,您可以使用设置方法更新值。您也可以使用添加方法来添加一个新的,或删除来删除该值。最后,调用的ToString()上的名称的NameValueCollection 返回名称值对在名1 =值1&放大器; 2 =值2 查询字符串准备格式。一旦你拥有它添加到URL和重定向。

The ParseQueryString method returns a NameValueCollection (actually it really returns a HttpValueCollection which encodes the results, as I mention in an answer to another question). You can then use the Set method to update a value. You can also use the Add method to add a new one, or Remove to remove a value. Finally, calling ToString() on the name NameValueCollection returns the name value pairs in a name1=value1&name2=value2 querystring ready format. Once you have that append it to the URL and redirect.

另外,您可以添加新的密钥,或修改现有的,使用索引:

Alternately, you can add a new key, or modify an existing one, using the indexer:

nameValues["temp"] = "hello!"; // add "temp" if it didn't exist
nameValues["temp"] = "hello, world!"; // overwrite "temp"
nameValues.Remove("temp"); // can't remove via indexer

您可能需要添加一个使用System.Collections.Specialized; 来利用的NameValueCollection 类的。

You may need to add a using System.Collections.Specialized; to make use of the NameValueCollection class.