When you intend to redirect after a Post, following the Post-Redirect-Get pattern but your previous view is constructed using a route parameter, then it would be sent to the redirect action too.
For instance, you are responding to a request for /Filter/Smartphone, where Smartphone is a route parameter, you Post it to some other controller action and at the end, you redirect to the Index action making use of the RedirectToAction method:
Return this.RedirectToAction(name of(Index));
The browser would issue the GET request for Index but takes the Smartphone route parameter, which is not fine.
The solution is to pass a routeValues parameter to RedirectToAction that do not have any of the possible route parameters. One way to do it is that you can create a dictionary with all action parameters zeroed:
return this.RedirectToAction(nameof(Index), MethodBase.GetCurrentMethod().GetParameters().ToDictionary(x => x.Name, x => (object) null));
The solution to do this automatically lies in the MethodBase.GetCurrentMethod() method. This way, you can surely avoid unwanted route parameters during your next request.
In case you wonder, passing null, a dictionary without object or entries would not work, the only other way is to pass an unknown value with the parameters set to null.
That’s it for now!
We give a well-structured program for the best Dot Net Course. Among various good institutes of dot net training and placement in Pune, CRB Tech has developed its own identity.