views:

459

answers:

4

Using the default route provided, I'm forced to name my parameters "id". That's fine for a lot of my Controller Actions, but I want to use some better variable naming in certain places. Is there some sort of attribute I can use so that I can have more meaningful variable names in my action signatures?

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

// Action Signature:
public ActionResult ByAlias(string alias)
{
  // Because the route specifies "id" and this action takes an "alias", nothing is bound
}
A: 

This still works, your query string will just look like "/Controller/ByAlias?alias=something".

Chris Shaffer
I guess you're saying it still works meaning if I had actually used Html.ActionLink to create my link, then it would create a URL as you've described... what if I didn't do that and just hit the URL /Controller/ByAlias/aliashere -- can I somehow bind the string alias parameter to the "id" piece defined in the route?
Langdon
A: 

You can customize the routes with whatever identifiers you like..

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

Edit: Here's an overview from the ASP.NET site

curtisk
I sure can, but if I still want the original /Home/Index/id to work, I can't very well define /Home/Index/alias right after it and expect it to ever get hit.
Langdon
A: 

Just because your route uses the name "id" for the ID variable doesn't mean that you have to use the same name in your controller action methods.

For example, given this controller method...

public Controller MailerController
{
    public ActionResult Details(int mailerID)
    {
        ...
        return View(new { id = mailerID });
    }
}

...and this action method call from the view...

<%= Html.ActionLink("More Info", "Details", new { mailerID = 7 }) %>

...you can use whatever naming convention you wish for the ID parameter in your controller action methods. All you need to do is resolve the new name to the default, whether it's "id", "alias", or whatever.

The above example should resolve to :

<a href="/Mailer/Details/7">More Info</a>
Neil T.
For me (in MVC 1.0) mailerID will always result in null if I hit /Mailer/Details/7. As soon as I change int mailerID to int id (as per the Route) it works fine.
Langdon
using `id` allows you to generalize your routes. Without this, you would need one route for every naming variation of id.
Robert Harvey
+6  A: 

Use the [Bind] attribute:

public ActionResult ByAlias([Bind(Prefix = "id")] string alias) {
    // your code here
}
Levi