So I have a C# .NET project.
On certain pages I need to change a parameter passed through the ActionResult but still keep the original URL.
In order to change the parameter to the one I needed, I changed the variable through the ActionContext. But this then changes the URL to the parameter - which is expected but not wanted.
public class CustomController : Controller {
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
if (isReplaceType) {
// replace action parameter to needed one
filterContext.ActionParameters["variable1"] = replacedVariable;
// Fake URL code here ??? ----------------
}
base.OnActionExecuting(filterContext);
}
}
I need to change site.com/replacedVariable to site.com/originalVariable in the user's browser URL bar.
How can I do this?
EDIT: Route looks like this in Global.asax
routes.MapRoute(
name: "HomeDefault",
url: "{variable1}/{action}",
defaults: new { controller = "home", action = "index" },
namespaces: new string[] { "Project.Controllers" }
);
After reading through this question: Change URL After Action is Hit MVC? It suggests that the only way to change the URL is to redirect the page - meaning changing an action variable was not the reason why the URL changed to the new variable.
I found that the page redirected in certain cases and this is why it changed. Hence, in order to fix it, I have overridden the Redirect function and replaced the new variable with the old value in the URL.
public class CustomController : Controller {
protected override RedirectResult Redirect(string url) {
if (Session["replacedVariable"] == null) {
return base.Redirect(url);
}
string replaceUrl = url.Replace("/" + Session["replacedVariable"], "/originalVariable");
return base.Redirect(replaceUrl);
}
}