Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Routing - Parameter names question

I'm looking for some information on Routing in MVC with C#. I'm currently very aware of the basics of routing in MVC, but what i'm looking for is somewhat difficult to find.

Effectively, what I want to find is a way of defining a single route that takes a single parameter.

The common examples I have found online is all based around the example

routes.MapRoute(
    "Default",
    "{controller}.mvc/{action}/{id}"
    new { controller = "Default", action="Index", id=""});

By mapping this route, you can map to any action in any controller, but if you want to pass anything into the action, the method parameter must be called "id". I want to find a way around this if it's possible, so that I don't have to constantly specify routes just to use a different parameter name in my actions.

Has anyone any ideas, or found a way around this?

like image 430
Jimmeh Avatar asked Dec 05 '08 12:12

Jimmeh


3 Answers

If you want to have a different parameter name and keep the same routing variable, use the FromUri attribute like so:

public ActionResult MyView([FromUri(Name = "id")] string parameterThatMapsToId)
{
   // do stuff
}

In your routes, all you need is:

routes.MapRoute(
  "Default",
  "{controller}.mvc/{action}/{id}"
  new { controller = "Default", action="Index", id=""});
like image 72
Curtis Avatar answered Oct 17 '22 10:10

Curtis


I don't think that you can do exactly what you are asking. When MVC invokes an action it looks for parameters in routes, request params and the query string. It's always looking to match the parameter name.

Perhaps good old query string will meet your needs.

~/mycontroller/myaction/?foobar=123

will pass 123 to this action:

public ActionResult MyAction(int? foobar)
like image 24
Tim Scott Avatar answered Oct 17 '22 10:10

Tim Scott


I know this is centuries ago, but hope it still helps someone. I asked the same question before. I think this is what you are looking for. An answer quoted from my question post: "The {*pathInfo} bit is called a slug. it's basically a wildcard saying "everything after this point is stuffed into a parameter called pathInfo". Thus if you have "{resource}.axd/{*pathInfo}" and a url like this: http://blah/foo.axd/foo/bar/baz/bing then two parameters get created, one called resource, which would contain foo and one called pathInfo which contains foo/bar/baz/bing."

like image 3
Tom Avatar answered Oct 17 '22 11:10

Tom