我正在实现一个自定义控件,在这个控件中我需要编写一堆指向当前页面的链接,每个链接都有不同的查询参数。我需要保持现有查询字符串完整,并添加(或修改 的值)额外的查询项(例如“页”):

"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"

ETC。

是否有一个简单的辅助方法可以在 Render 方法中使用...嗯……喜欢:

Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");

这将负责生成正确的 URL、维护现有的查询字符串项并且不会创建重复项,例如。页=1&页=2&页=3?

自己卷起来似乎是一项没有吸引力的任务。

有帮助吗?

解决方案

恐怕我不知道有任何内置方法,我们使用这个接受查询字符串并设置参数的方法

    /// <summary>
    /// Set a parameter value in a query string. If the parameter is not found in the passed in query string,
    /// it is added to the end of the query string
    /// </summary>
    /// <param name="queryString">The query string that is to be manipulated</param>
    /// <param name="paramName">The name of the parameter</param>
    /// <param name="paramValue">The value that the parameter is to be set to</param>
    /// <returns>The query string with the parameter set to the new value.</returns>
    public static string SetParameter(string queryString, string paramName, object paramValue)
    {
        //create the regex
        //match paramname=*
        //string regex = String.Format(@"{0}=[^&]*", paramName);
        string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName);

        RegexOptions options = RegexOptions.RightToLeft;
        // Querystring has parameters...
        if (Regex.IsMatch(queryString, regex, options))
        {
            queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue));
        }
        else
        {
            // If no querystring just return the Parameter Key/Value
            if (queryString == String.Empty)
            {
                return String.Format("{0}={1}", paramName, paramValue);
            }
            else
            {
                // Append the new parameter key/value to the end of querystring
                queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue);
            }
        }
        return queryString;
    }

显然你可以使用 QueryString NameValueCollection URI 对象的属性,以便更轻松地查找值,但我们希望能够解析任何查询字符串。

其他提示

哦,我们也有这个方法,它允许您输入整个 URL 字符串,而不必从中取出查询字符串

public static string SetParameterInUrl(string url, string paramName, object paramValue)
{
    int queryStringIndex = url.IndexOf("?");
    string path;
    string queryString;
    if (queryStringIndex >= 0 && !url.EndsWith("?"))
    {
        path = url.Substring(0, queryStringIndex);
        queryString = url.Substring(queryStringIndex + 1);
    }
    else
    {
        path = url;
        queryString = string.Empty;
    }
    return path + "?" + SetParameter(queryString, paramName, paramValue);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top