Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - How to pass Request.QueryString to Url.Action?

I'm building an url using the method:

Url.Action("action", "controller");

I like to pass the querystring for the current request into that url as well. Something like the following (but it doesn't work):

Url.Action("action", "controller", Request.QueryString);

Converting the QueryString to routevalues is possible with the following extension:

    public static RouteValueDictionary ToRouteValues(this NameValueCollection queryString)
    {
        if (queryString.IsNull() || queryString.HasKeys() == false) return new RouteValueDictionary();

        var routeValues = new RouteValueDictionary();
        foreach (string key in queryString.AllKeys)
            routeValues.Add(key, queryString[key]);

        return routeValues;
    }

With the extension method the following does work:

Url.Action("action", "controller", Request.QueryString.ToRouteValues());

Is there an other better way ? Thx

question from:https://stackoverflow.com/questions/5818065/how-to-pass-request-querystring-to-url-action

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to easily be able to add additional route value parameters to your Url.Action, try this extension method (based on Linefeed's) which takes an anonymous object and returns a RouteValueCollection:

public static RouteValueDictionary ToRouteValues(this NameValueCollection col, Object obj)
{
    var values = new RouteValueDictionary(obj);
    if (col != null)
    {
        foreach (string key in col)
        {
            //values passed in object override those already in collection
            if (key != null && !values.ContainsKey(key)) values[key] = col[key];
        }
    }
    return values;
}

Then you can use it like so:

Url.Action("action", "controller", Request.QueryString.ToRouteValues(new{ id=0 }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...