setting query string in redirecttoaction in asp.net mvc

前端 未结 2 892
谎友^
谎友^ 2020-12-17 02:14

I have to do a redirecttoaction call in asp.net mvc view with varying params, extracted from the referrer page of the view (the status of a grid).

I hav

相关标签:
2条回答
  • 2020-12-17 02:33

    One limitation of using RedirectToAction("actionName", {object with properties}) is that RedirectToAction() has no overload which accepts RedirectToAction(ActionResult(), {object with properties}), so you are forced to use magic strings for the action name (and possibly the controller name).

    If you use the T4MVC library, it includes two fluent API helper methods (AddRouteValue(...) and AddRouteValues(...)) which enable you to easily add a single querystring parameter, all properties of an object, or the whole Request.QueryString. You can call these methods either on T4MVC's own ActionResult objects or directly on the RedirectToAction() method. Of course, T4MVC is all about getting rid of magic strings!

    As an example: suppose you want to redirect to a login page for a non-authenticated request, and pass the originally requested URL as a query string parameter so you can jump there after successful login. Either of the following syntax examples will work:

    return RedirectToAction(MVC.Account.LogOn()).AddRouteValue(@"returnUrl", HttpUtility.UrlEncode(Request.RawUrl));
    

    or

    return RedirectToAction(MVC.Account.LogOn().AddRouteValue(@"returnUrl", HttpUtility.UrlEncode(Request.RawUrl)));
    
    0 讨论(0)
  • 2020-12-17 02:40

    To create a generic solution convert your querystring to a Dictionary and at the dictionary to the RouteValueDictionary.

    var parsed = HttpUtility.ParseQueryString(temp); 
    Dictionary<string,object> querystringDic = parsed.AllKeys
        .ToDictionary(k => k, k => (object)parsed[k]); 
    
    return RedirectToAction("Index", new RouteValueDictionary(querystringDic)); 
    
    0 讨论(0)
提交回复
热议问题