Search code examples
asp.net-mvccontrollersredirecttoaction

How to redirect to a specific URL from within a controller?


I am trying to redirect user to a specific address, after they submit a form. What I use is the code below in my Content controller:

return RedirectToAction("Business", new RouteValueDictionary(new { controller = "Content", action = "Business", Id = business.BusinessID }));

It creates a URL like this : www.x.com/Content/Business?Id=13

What I really want is something like this: www.x.com/Content/Business/13

I really don't want the query string to be separated with ? but to be consistent with the rest of the URLs.

Is there anyway to do so?


Solution

  • The code should actually be the same thing, but the thing to note is in the Global.asax file, where I setup my routing table, I need to have the following piece of code so that my desired result be produced. Notice the third url parameters {parameter}

    routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{parameter}", // URL with parameters
                    new { controller = "Tokens", action = "Index", parameter = UrlParameter.Optional } // Parameter defaults
                );
    

    with that code, I only need to use the variable "parameter" instead of "Id" in my code:

    return RedirectToAction("Business", new RouteValueDictionary(new { controller = "Content", action = "Business", parameter= business.BusinessID }));
    

    It is very important to use the same name for your variable as you defined in MapRout() function.

    Doing this, I have my desired result :

    www.x.com/Content/Business/13