Search code examples
c#asp.net-mvcasp.net-mvc-routing

Pass parameters through URL in an ASP.NET MVC Application


I need to access a parameter without name. Ex: I have a controller test, I want to get "data" in mysite.com/test/data. Without calling the action data. I know how to do that passing it though Index action.

public ActionResult Index(string id)

That way I'd only need to type mysite.com/test/Index/data to get "data", but I don't want to have to type Index.

Does anyone know how to do it?

EDIT:

Thanks a lot to @andyc!

AndyC I used what you said and created a test. It worked =D

Now I can type mysite.com/something and if something is not an controller it redirects to my profile page.

This is what is working for me

routes.MapRoute(
      "Profile",
      "{id}",
      new { Controller = "Profile", action = "Index", id = UrlParameter.Optional }
);

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

Solution

  • Setup a custom route

    In your global.asax file, put (Inside the RegisterRoutes method):

    routes.MapRoute(
        "MyShortRoute",
        "view/{id}",
        new { Controller = "test", action = "Index" }
    );
    

    The first parameter is a name, the second is the URL format and the last parameter is the default values (in this case if you leave id empty it'll default to id 0.

    Notice that I don't use test/{id} as this would also match test/Edit, where edit is an action that you do not want passed as a parameter (I can't think of another way to avoid this, especially if you're using strings instead of ints for your parameters).

    Remember to order your routes appropriately in your global.asax file. Put more specific routes before less specific routes. When the system is searching for a route to take, it does not attempt to find the most specific match but instead it starts from the top, and uses the first match it finds.

    Therefore, this is bad:

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "test", action = "Index", id = UrlParameter.Optional }
    );
    routes.MapRoute(
        "Specific",
        "test/{id}",
        new { controller = "test", action = "Index", id = 0 } 
    );
    

    In this example, if you browse to test/somevalue it will match the FIRST entry, which is not what you want, giving you the testcontroller and the somevalue action.

    (As your adding a more specific route, you will want it near the top, and definitely before your default).