5

I have an action taking two GUIDs:

public class MyActionController : Controller
{
  //...

  public ActionResult MoveToTab(Guid param1, Guid param2)
  {
    //...
  }
}

I would like the following URI to map to the action:

/myaction/movetotab/1/2

...with 1 corresponding to param1 and 2 to param2.

What will the route look like, and is it possible to map the arguments to parameters with a type of Guid?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Ben Aston
  • 53,718
  • 65
  • 205
  • 331

2 Answers2

8

Yes, it is possible to map your parameters to System.Guid

routes.MapRoute(
    "MoveToTab",
    "{controller}/{action}/{param1}/{param2}",
    new { controller = "MyAction", action = "MoveToTab",
        param1 = System.Guid.Empty, param2 = System.Guid.Empty }
);

or

routes.MapRoute(
    "MoveToTab2",
    "myaction/movetotab/{param1}/{param2}",
    new { controller = "MyAction", action = "MoveToTab",
        param1 = System.Guid.Empty, param2 = System.Guid.Empty }
);
eu-ge-ne
  • 28,023
  • 6
  • 71
  • 62
  • check your params...I think the second one should be param2 not param1. – Robert Harvey Jan 11 '10 at 16:41
  • Does this work because Guid takes a string as a parameter in one of its constructor overloads, or does the MVC framework cast the incoming string from the URL to a Guid? Will this process work for any object? – Robert Harvey Jan 11 '10 at 19:28
  • This things are handled by MVC framework (DefaultModelBinder) – eu-ge-ne Jan 11 '10 at 20:25
  • Be careful using this. It'll work fine if your users are clicking on links, but if they ever type in something like `controller/action/abc123`, you'll get an exception saying that Guid cannot be null (naturally, since `abc123` can't be made into a valid Guid). A workaround would be to make the Guid nullable in the controller, but then you have the weirdness that an empty Guid means no Guid was provided and a null Guid is an invalid Guid. – Daniel T. Jan 14 '10 at 05:00
3

You can take in your two GUIDs as strings, and convert them to actual GUID objects using the GUID constructor that accepts a string value. Use the route that eu-ge-ne provided.

routes.MapRoute(
    "MoveToTab",
    "myaction/movetotab/{param1}/{param2}",
    new { controller = "MyAction", action = "MoveToTab", param1 = "", param2 = "" }
);

  public ActionResult MoveToTab(string param1, string param2)
  {
    Guid guid1 = new Guid(param1);
    Guid guid2 = new Guid(param2);
  }
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501