I want to make sure that a particular parameter in the QueryString, in my case the request_id
is propagated to the redirected action.
Say for example, I have an Action First
,
[HttpPost]
public ActionResult First()
{
////////////////////
// Lots of code ...
////////////////////
return RedirectToAction("Second");
}
Now say, the First
postback had a parameter in the QueryString
, which I would like to pass to the Second
action. One way to do it would be to pass the value in the RedirectToAction
call itself,
string requestId = Request.QueryString[REQUEST_ID_KEY];
return RedirectToAction("Second", new { REQUEST_ID_KEY = requestId });
But I have to do this in a series of Actions and I am unwilling to incorporate request id propagation logic inside the action. It would be better if I could incorporate this inside an ActionFilter
, but I cant figure out how to add parameters to the QueryString from an ActionFilter. Any ideas?
A querystring is a set of characters input to a computer or Web browser and sent to a query program to recover specific information from a database .
A Query String collection is a parsed version of the QUERY_STRING variable in the Server Variables collection. It enable us to retrieve the QUERY_STRING variable by name. When we use parameters with Request. QueryString, the server parses the parameters sent to the request and returns the effective or specified data.
My Question - Can I pass student model in RedirectToAction? Since the route dictionary deals with objects, try changing the GetStudent action to accept an object and inside cast it to Student . Another option would be to serialize it using JSON when passing it from FillStudent .
public class PreserveQueryStringAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var redirectResult = filterContext.Result as RedirectToRouteResult;
if (redirectResult == null)
{
return;
}
var query = filterContext.HttpContext.Request.QueryString;
// Remark: here you could decide if you want to propagate all
// query string values or a particular one. In my example I am
// propagating all query string values that are not already part of
// the route values
foreach (string key in query.Keys)
{
if (!redirectResult.RouteValues.ContainsKey(key))
{
redirectResult.RouteValues.Add(key, query[key]);
}
}
}
}
and then:
[HttpPost]
[PreserveQueryString]
public ActionResult First()
{
////////////////////
// Lots of code ...
////////////////////
return RedirectToAction("Second");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With